JavaScript中的'call'是如何工作的?

9
我有一个关于JavaScript中“call”的问题。
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();

那么,当我使用'call'函数,将humanWithHand.call(this)传递进去时,内部会发生什么?

humanWithHand变量是否将其属性和成员复制(或指向)到human变量的原型中?


MDN文档 call() - epascarello
2个回答

11

耶胡达·卡茨(Yehuda Katz)对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指的是最右侧句点左侧的对象,例如在这个例子中,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"`

很好的解释 - ARK

8

.call() 方法设置了 this 值,然后使用你传递给 .call() 的参数调用该函数。当你想要在被调用的函数内部设置 this 值,而不是让它被设置为 JavaScript 通常设置的值时,你可以使用 .call() 方法代替直接调用函数。

.apply() 是一个姐妹函数。它也可以设置 this 值,并且可以使用数组作为参数,因此可以在尝试从其他函数调用中传递可变参数列表或以编程方式构造参数列表时使用,这些列表可能根据情况有不同数量的参数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接