在JavaScript原型函数中保留对“此”的引用
this
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.myValueMyClassthis
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;thisdoSomethingjQueryMyClass
thisMyClass
饮歌长啸
慕莱坞森
相关分类