【问题标题】:How does 'call' work in javascript?“调用”在 JavaScript 中是如何工作的?
【发布时间】:2011-11-08 02:21:42
【问题描述】:

我对 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 变量是否将其属性和成员复制(或指向?)到人类变量的原型?

【问题讨论】:

标签: javascript call


【解决方案1】:

Yehuda Katz 拥有 JavaScript 的 Function#call 方法的 a good writeup。他的文章应该回答你的问题,以及许多后续问题。

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

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

那么函数调用内部的this 就是函数调用外部的this。默认情况下,在浏览器中,任何函数调用之外的thiswindow。所以在上面的函数调用里面,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"`

【讨论】:

  • 很好的解释
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2012-05-28
    • 2011-12-19
    • 2023-03-10
    • 1970-01-01
    • 2015-11-02
    • 2013-09-26
    • 2020-01-22
    • 2012-01-04
    • 2016-04-13
    相关资源
    最近更新 更多