<分区>
我刚刚开始使用原型(prototype) JavaScript,但我无法弄清楚如何在作用域发生变化时从原型(prototype)函数内部保留对主对象的 this
引用。让我来说明我的意思(我在这里使用 jQuery):
MyClass = function() {
this.element = $('#element');
this.myValue = 'something';
// some more code
}
MyClass.prototype.myfunc = function() {
// at this point, "this" refers to the instance of MyClass
this.element.click(function() {
// at this point, "this" refers to the DOM element
// but what if I want to access the original "this.myValue"?
});
}
new MyClass();
我知道我可以通过在 myfunc
的开头这样做来保留对主对象的引用:
var myThis = this;
然后使用 myThis.myValue
访问主对象的属性。但是当我在 MyClass
上有一大堆原型(prototype)函数时会发生什么?我是否必须在每个代码的开头保存对 this
的引用?似乎应该有一种更清洁的方法。那么像这样的情况呢:
MyClass = function() {
this.elements $('.elements');
this.myValue = 'something';
this.elements.each(this.doSomething);
}
MyClass.prototype.doSomething = function() {
// operate on the element
}
new MyClass();
在这种情况下,我无法使用 var myThis = this;
创建对主对象的引用,因为即使 this
的原始值在 doSomething
是一个 jQuery
对象,而不是一个 MyClass
对象。
有人建议我使用一个全局变量来保存对原始 this
的引用,但这对我来说似乎是一个非常糟糕的主意。我不想污染全局命名空间,这似乎会阻止我实例化两个不同的 MyClass
对象,而不会相互干扰。
有什么建议吗?有没有一种干净的方法来做我想要做的事情?还是我的整个设计模式有缺陷?