【问题标题】:JavaScript: how to call a function on the prototype property, from inside another function on the prototype property, all inside a closure?JavaScript:如何从原型属性上的另一个函数内部调用原型属性上的函数,全部在闭包内?
【发布时间】:2015-06-25 21:02:52
【问题描述】:

我希望有人可以帮助我弄清楚如何正确地做到这一点,而不仅仅是“让它发挥作用”。

我正在尝试在闭包内使用对象,但存在范围问题:

var Why = function() {
    this.foo = 'bar';
}
Why.prototype.explain = function () {
    alert(this.foo);
}
Why.prototype.doIt = function () {
    this.explain();
}

(function() {

    document.addEventListener("DOMContentLoaded", function(event) {
        var why = new Why();
        why.doIt();
    });

})();

然后我进入控制台:

Uncaught TypeError: this.explain is not a function

我可以使用

Why.prototype.explain.call();

但这似乎是错误的,当我真正这样做时...... this.foo 无论如何都是未定义的, 所以这显然不是正确的方法。

如果我删除自调用函数如下...

var Why = function() {
    this.foo = 'bar';
}
Why.prototype.explain = function () {
    console.log(this.foo);
}
Why.prototype.doIt = function () {
    // Why.prototype.explain.call();
    this.explain();
}

// (function() {

    document.addEventListener("DOMContentLoaded", function(event) {
        var why = new Why();
        why.doIt();
    });

// })();

那么它当然可以工作,但是:

我缺少什么以及我在哪里/如何学习它?

提前致谢。

【问题讨论】:

  • 简单:在赋值后加分号,你不会相信发生了什么......

标签: javascript scope closures prototype


【解决方案1】:

你的代码被解析为

Why.prototype.doIt = function () { ... }(function() { ... });

您正在调用要分配给原型的函数,然后分配其返回值。因为它返回undefined,所以Why.prototype.doIt不存在。

你需要一个分号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-17
    相关资源
    最近更新 更多