---
title: "javascript核心 -- function "
author: "编程足球"
date: "2013-03-22T11:14:43Z"
tags: []
categories: ["Web前端"]
slug: "javascript-function"
draft: false
lastmod: "2013-03-22T11:06:07Z"
id: 1832964
url: "https://lingf.iteye.com/blog/1832964"
---

<span style="color:red">1. 调用</span>
1.1 函数调用

```js

function f(){
     // TODO xxxx   
}

f();// 函数调用

```


1.2方法调用

```js

var obj = {
    m:function(){
       // TODO xxxx   
    }
}


obj.m();

```


区别:
<span style="color:red">函数调用</span>在ECMAScript3和非严格下的ECMAScript5调用的上下文是(this)全局对象,但是在严格模式下调用的上下文是undefined

<span style="color:red">方法调用</span>上下文 this指向本身

eg


```js

var obj = {
    m:function(){
        var self = this;
        console.log(this === obj); // true
    
        f();
        
        function f(){
            console.log(this === obj);  //false;
            console.log(this);       // this 为undefined 或者为全局上下文对象
            console.log(self === obj); // true
            
        }
        
        return this;
    }
}

obj.m();

```


<span style="color:red">2. 传递参数</span>
2.1 少传递   --> 变成undefined

```js

function f(a,b,c){

    console.log(a); // a = 1
    console.log(b); // b = 2
    console.log(c); // c = undefined

}

f(1,2);

```


2.2 多传递  --> 通过 arguments来获取

```js

function f(a){
    console.log(a);  // 1
    console.log(arguments.length); //2
    console.log(arguments[0]);  //1 == a
    console.log(arguments[1]);  //2 == 第二个参数
    console.log(arguments[2]);  //undefined
}

f(1,2);

 

```

<span style="color:red">注: arguments 并不是数组,只是碰巧用数字做索引,以及一个length属性</span>


2.3. arguments的两个属性callee 与 caller

在非严格模式下,callee 指:<span style="color:green">当前正在执行的函数</span>
caller 指:<span style="color:green">调用当前正在执行的函数的函数</span>

```js

var f = function(x){
    if(x <=1){
        return 1;
    }
    return x*arguments.callee(x-1);
}
f(5);  // 进行递归调用 120

```


<span style="color:red">3. 做值的函数</span>

```js

function square(x){
    return x*x;
}
var s = square;
square(4);//16
s(5); //25

/** 
* a[0]: 是一个function
* a[1]: 20
*/
var a = [function square(x){return x*x;},20];
a[0](a[1]); //400

//操作数,function作为参数传递
function add(x,y){
    return x+y;
}
function operate(operator,operand1,operand2){
    return operator(operand1,operand2);
}

operate(add,1,2);

```