我刚刚开始使用原型 JavaScript,我无法弄清楚如何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
?我是否必须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
不相互干扰的情况下实例化两个不同的对象。
有什么建议?有没有一种干净的方法来做我所追求的?还是我的整个设计模式有缺陷?