【问题标题】:Extending prototype within anonymous function - strange effects在匿名函数中扩展原型 - 奇怪的效果
【发布时间】:2015-01-02 03:41:20
【问题描述】:

在尝试创建私有静态方法的方法时,我遇到了这种非常奇怪的行为。在下面的代码中,公共方法 getData 被它自己的返回数据覆盖,尽管它从未被显式调用!这对我来说很奇怪,想知道这里发生了什么。我想它不仅可以按照模块模式在匿名函数中包含整个页面,而且我仍然想了解这个错误。

function MyClass() {
    this._prop = true;
}
MyClass.prototype.getData = function () {
    this._prop = false;
    return { a: 2344, b: 765, c: 234 };
}

(function () {
    var privateStatic = 0;
    MyClass.prototype.getCount = function () {
        return privateStatic++;
    }
} ());

var m = new MyClass();
console.log(m.getData()); //Error (object is not a function)
console.log(m.getData); //prints {a:2344,b:765,c:234}

【问题讨论】:

  • 在getData方法赋值后需要一个semi(;);这是一种表达方式。否则,该函数将传递您的匿名结果,并将结果分配给 instance.getData

标签: javascript closures anonymous-function


【解决方案1】:

这种奇怪行为的原因是 getData 被立即调用,因为函数声明后缺少分号(很棒的地方,dandavis)和紧随其后的 IIFE,用括号括起来。本质上是这样的:

MyClass.prototype.getData = function () {
  this._prop = false;
  return { a: 2344, b: 765, c: 234 };
} // Notice no semicolon here!
(function () {
  var privateStatic = 0;
  MyClass.prototype.getCount = function () {
    return privateStatic++;
  }
} ());

变成这样:

MyClass.prototype.getData = function () {
  this._prop = false;
  return { a: 2344, b: 765, c: 234 };
}();

因此将 getData 属性设置为函数的返回值。因此为什么m.getData 打印出{ a: 2344, b: 765, c: 234 }m.getData() 不起作用(它不再是一个函数!)。

【讨论】:

  • Javascript 中的可选分号又来了!感谢 jayrobin 和 dandavis 解释了似乎是最黑暗的黑魔法。
猜你喜欢
  • 2013-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多