“call”在javascript中是如何工作的?

How does 'call' work in javascript?

提问人:Moon 提问时间:9/1/2011 更新时间:9/1/2011 访问量:2846

问:

我有一个关于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();

所以。。当我使用'call'作为humanWithHand.call(this)时,内部会发生什么?

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

JavaScript 调用

评论

0赞 epascarello 9/1/2011
MDN 文档 call()

答:

11赞 yfeldblum 9/1/2011 #1

Yehuda Katz 对 JavaScript 的方法有很好的描述。他的文章应该回答你的问题,此外还有许多后续问题。Function#call

直接调用函数时,使用常规语法:

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

然后,函数调用内部是函数调用外部的任何内容。默认情况下,在浏览器中,任何函数调用的外部都是 。所以里面的函数调用如上,也是默认的。thisthisthiswindowthiswindow

使用 method-call 语法调用函数时:

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

然后在函数调用中是最右边句点左边的对象:在本例中为 .thisbar

我们可以使用 来模拟这种情况。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赞 ARK 11/5/2017
很好的解释
8赞 jfriend00 9/1/2011 #2

.call()设置该值,然后使用传递给 的参数调用函数。当您想在被调用的函数中设置值时,您可以使用而不是直接调用函数,而不是将其设置为 javascript 通常将其设置为的任何值。this.call().call()this

.apply()是姊妹函数。它还可以设置值,并且可以接受数组中的参数,因此当您尝试从其他函数调用传递变量参数列表时,或者当您以编程方式构造参数列表时,可以使用它,该列表可能具有不同数量的参数,具体取决于情况。this