2011-09-01 38 views
8

我有一个关于JavaScript的'调用'的问题。'call'如何在JavaScript中工作?

var humanWithHand = function(){ 
    this.raiseHand = function(){ 
     alert("raise hand"); 
    } 
} 

var humanWithFoot = function(){ 
    this.raiseFoot = function(){ 
     alert("raise foot"); 
    } 
} 

var human = function(){ 

    humanWithHand.call(this); 
    humanWithFoot.call(this); 

} 

var test = new human(); 

so..when我使用'call'作为humanWithHand.call(this),内部会发生什么?

是否将humanWithHand变量拷贝(或点?)的属性和成员赋值给人类变量的原型?

+0

[MDN文档调用()](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call) – epascarello

回答

7

.call()设置this值,然后调用与您传递给.call()参数的功能。您可以使用.call()而不是直接调用该函数,而不是在被调用函数内设置this值,而不是将其设置为javascript通常设置的值。

.apply()是姐妹功能。它还可以设置this值,它可以在数组中使用参数,以便在尝试从某个其他函数调用传递可变参数列表时或者在以编程方式构造可能具有不同数字的参数列表时使用它根据情况而定的论点。

9

Yehuda Katz has a good writeup JavaScript的Function#call方法。他的写作应该回答你的问题,还有许多后续问题。

当你直接调用一个函数,使用的一般语法:

var foo = function() { 
    console.log("foo"); 
    return this; 
}; 
foo(); // evaluates to `window` 

然后this函数调用里面是什么this是函数调用之外。默认情况下,在浏览器中,this以外的任何函数调用都是window。所以在上面的函数调用中,this也是默认的window

当调用使用的方法调用的语法的函数:

var bar = { 
    foo: function() { 
    console.log("foo"); 
    return this; 
    } 
}; 
bar.foo(); // evaluates to `bar` 

然后this函数调用内部是对象到最右边的周期的左边:在这种情况下,bar

我们可以使用call来模拟这种情况。

当您设置一个对象之外的功能,并希望与this调用它的函数调用设置到对象中,您可以:

var foo = function() { 
    console.log("foo"); 
    return this; 
} 
var bar = { }; 
foo.call(bar); // evaluates to `bar` 

您可以使用此技术来传递参数,以及:

var foo = function(arg1, arg2) { 
    console.log("foo"); 
    return arg1 + arg2; 
} 
var bar = { }; 
foo.call(bar, "abc", "xyz"); // evaluates to `"abcxyz"` 
+0

很好的解释 –