'call'如何在javascript中工作?

Moo*_*oon 9 javascript call

我在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();
Run Code Online (Sandbox Code Playgroud)

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

humanWithHand变量(或点?)将其属性和成员复制到人类变量的原型中?

yfe*_*lum 9

Yehuda Katz有很好的JavaScript Function#call方法.他的写作应该回答你的问题,以及许多后续问题.

使用通用语法直接调用函数时:

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

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

使用方法调用语法调用函数时:

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

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

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

在对象外部设置函数并希望this在设置为对象的函数调用内部调用它时,您可以:

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

您也可以使用此技术传递参数:

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


jfr*_*d00 8

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

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