我希望有人能帮助我弄清楚如何正确地做到这一点,而不仅仅是“让它发挥作用”。
我尝试在闭包内使用对象,但遇到范围问题:
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();
});
// })();
那么它当然可以工作,但是:
我缺少什么以及在哪里/如何学习它?
提前致谢。
最佳答案
您的代码被解析为
Why.prototype.doIt = function () { ... }(function() { ... });
您正在调用要分配给原型(prototype)的函数,然后分配其返回值。由于它返回 undefined
,因此 Why.prototype.doIt
不存在。
您需要一个分号。
关于JavaScript:如何从原型(prototype)属性上的另一个函数调用原型(prototype)属性上的函数,所有这些都在闭包内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31060734/