简体   繁体   English

JavaScript:如何从原型属性上的另一个函数内部调用原型属性上的函数,都在闭包内部?

[英]JavaScript: how to call a function on the prototype property, from inside another function on the prototype property, all inside a closure?

I am hoping that someone can help me figure out how to do this correctly, rather than just "make it work." 我希望有人能帮助我弄清楚如何正确地做到这一点,而不仅仅是“使其工作”。

I am trying to use an object inside a closure, and having scope issues: 我试图在闭包内使用一个对象,并遇到范围问题:

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();
    });

})();

And I get in console: 我进入控制台:

Uncaught TypeError: this.explain is not a function

I could use 我可以用

Why.prototype.explain.call();

but that just seems wrong, and when I actually do that... this.foo is undefined anyway, so it's obviously not the right approach. 但这似乎是错误的,而且当我实际执行此操作时... this.foo仍然是未定义的,因此显然不是正确的方法。

If I remove the self calling function as follows... 如果我按如下方式删除自调用函数...

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();
    });

// })();

then it works of course, but: 那么当然可以,但是:

what am I missing and where/how can I learn it? 我缺少什么,在哪里/如何学习?

Thanks in advance. 提前致谢。

Your code is parsed as 您的代码被解析为

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

You're calling the function you want to assign to the prototype, then assigning its return value. 您正在调用要分配给原型的函数,然后分配其返回值。 Since it returns undefined , Why.prototype.doIt doesn't exist. 由于返回undefinedWhy.prototype.doIt不存在。

You need a semicolon. 您需要分号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM