【发布时间】: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