【问题标题】:difference between functionName() and functionName.call(this)functionName() 和 functionName.call(this) 之间的区别
【发布时间】:2016-11-26 17:36:38
【问题描述】:

我研究 javascript 中的函数继承。 根据我阅读的文章,我已经编写了代码:

function Base(){
    var enableVar = true

  this.enable = function(){
      console.log("enable");
        enableVar = true;
  }
   this.disable = function(){
      console.log("disable");
        enableVar = true;
  }
}

function Child(){
    Base.call(this);
}

new Child().enable();

此代码运行正常,我在控制台中看到消息。

但我不明白行:

Base.call(this);

对我来说,它是 Base 函数调用 this 替换为 this 因此它与 Base(); 相同

但是看起来我的状态是错误的。我看到错误:

VM898:62Uncaught TypeError: (intermediate value).enable is not a function(…)

请为我澄清差异。

更新

function funcB(){
  return this.a;
}

function funcA(){
  this.a = 2;   
  return funcB();
}
alert(funcA());

虽然我像 funcB(); 一样调用 funcB,但此代码会发出警报 2

我真的不明白区别

【问题讨论】:

标签: javascript inheritance this


【解决方案1】:

functionName.call(obj) 调用functionName 正常,有一个主要区别:functionName 的内部,this 指的是obj。通常this 指代window,但使this 引用obj 非常有利于继承,因为您可以在所有构造函数中继续使用this

编辑(解释更新):

这是你的代码:

function funcB(){
  return this.a;
}

function funcA(){
  this.a = 2;   
  return funcB();
}
alert(funcA());

我们将逐步完成此操作。实际运行的第一件事是alert(funcA());,它调用funcA()。默认情况下,该代码将this 视为等于window(窗口是javascript 的全局变量容器)。所以计算机认为下一步(执行funcA)是这样的:

function funcA(){
  window.a = 2;   
  return funcB();
}

该代码将全局变量a 设置为2,并将返回funcB 返回的任何内容,因此我们将看看funcB。请记住,默认情况下,javascript 设置this = window,所以funcB 实际上是

function funcB(){
  return window.a;
}

请记住,我们将window.a = 2 设置回funcA,所以funcB 变为

function funcB(){
  return 2;
}

这意味着funcA变成了

function funcA(){
  window.a = 2;   
  return 2;
}

这意味着alert(funcA());变成alert(2);

【讨论】:

  • this 成为草率模式下的全局对象。在严格模式下是undefined
  • @gstackoverflow 更新了我的答案
【解决方案2】:

首先,想想new 做了什么。它创建一个新对象,该对象是您指定的函数的实例。所以new Child基于Child创建了一个新对象

Base.call(this) 表示“运行Base 函数,就像新创建的Child 对象作为上下文一样”(其中“上下文”表示“this 的内部值)。这意味着enabledisable 函数被添加到新的 Child 对象中。

现在想想调用Base() 的作用。没有新的Base 对象。因此函数中没有this 的值。新的Child 对象没有被修改,所以当你调用.enable() 时,该函数还不存在,你会得到你提到的错误。

【讨论】:

  • @onesomeday现在想想调用 Base() 的作用。没有新的 Base 对象。因此,函数中没有 this 的值。请澄清这一点
  • @gstackoverflow 正确,没有新的 Base 对象。但是在您的第一个示例中,有一个新的 Child 对象,它继承自 Base。
猜你喜欢
  • 2011-02-20
  • 1970-01-01
  • 1970-01-01
  • 2013-10-23
  • 2012-08-18
  • 1970-01-01
  • 2017-12-22
  • 2012-03-15
  • 1970-01-01
相关资源
最近更新 更多