我刚开始使用原型式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
对象而不会干扰彼此。有什么建议吗?有没有一种干净的方式来做我想要的事情?还是我的整个设计模式有缺陷?
Function.prototype.bind
这个名称。它已成为语言的标准化部分,不会消失。 - bobince$.proxy(obj.fx, obj)
或者$.proxy(obj, "fx")
。 - Rob Van Dam