[英]JavaScript: how to call a function on the prototype property, from inside another function on the prototype property, all inside a closure?
我希望有人能帮助我弄清楚如何正确地做到这一点,而不仅仅是“使其工作”。
我试图在闭包内使用一个对象,并遇到范围问题:
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() { ... });
您正在调用要分配给原型的函数,然后分配其返回值。 由于返回undefined
, Why.prototype.doIt
不存在。
您需要分号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.