【发布时间】:2011-01-02 19:18:52
【问题描述】:
我刚刚开始使用原型 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; 创建对主对象的引用,因为即使doSomething 上下文中this 的原始值也是jQuery 对象而不是MyClass对象。
有人建议我使用一个全局变量来保存对原始this 的引用,但这对我来说似乎是一个非常糟糕的主意。我不想污染全局命名空间,这似乎会阻止我实例化两个不同的 MyClass 对象,而不会相互干扰。
有什么建议吗?有没有一种干净的方法来做我所追求的?还是我的整个设计模式有缺陷?
【问题讨论】:
标签: javascript oop scope this prototype-programming