2009-07-27 58 views
2

對不起,如果這已被回答,但我無法找到它...一個困難的事情來搜索,我想!在JavaScript(和jQuery.extend)中確定「this」

說我有這樣的:

var MyPrototype = function() { this.init(); } 
$.extend(MyPrototype.prototype, { 
    a: 5, 
    init: function() { 
     var thing = new SomeOtherClass(); 
     thing.meth = this.meth; 
     // thing.meth() is called somewhere within thing; 
    }, 
    meth: function() { 
     alert(this.a); 
    } 
} 

基本上,我處理的,它使用自己的方法爲回調,如其他類我希望用我自己的功能覆蓋它們。但我在做這件事的時候需要保留this的適當範圍(我關心的SomeOtherClass唯一關心的是傳遞給回調的東西;狀態中沒有任何東西)。

如你所想,這不起作用,因爲thing沒有a屬性!我並不熟悉JavaScript的複雜性範圍,知道如何使this參考我想要的東西,不過!

+0

請參閱:http://stackoverflow.com/questions/520019/controlling-the-value-of-這在一個jQuery的事件...還有:http://stackoverflow.com/questions/1043556/how-can-i-keep-the-context-of-this-in-jquery ...和真的,大多數問題在:http://stackoverflow.com/questions/tagged/this+javascript(這是一個非常常見的混淆點) – Shog9 2009-07-27 22:44:40

回答

2

這裏結合其他兩個答案,讓你不不得不重寫你的方法,我會這樣做:

var me = this; 
    thing.meth = function() { 
     MyPrototype.meth.apply(me, arguments); 
    }; 
-1

如何:

thing.meth.call(this); 

thing.meth.apply(this); 

(唯一的區別是如何將參數傳遞,這並不在此情況下,無所謂。)

+0

不幸的是,因爲它們是從`SomeOtherClass`發起的回調,所以我不實際上控制着他們如何被調用。 – tdavis 2009-07-27 21:46:53

+0

在這種情況下,您只需要將回調封裝在閉包中,以便將「this」的值與函數引用一起攜帶。 * edsoverflow *已經發布了一個例子。 – 2009-07-27 22:23:01

-1

你知道像這樣?

var MyPrototype = function() { this.init(); } 
$.extend(MyPrototype.prototype, { 
    a: 5, 
    init: function() { 
     var thing = new SomeOtherClass(); 
     var self = this; 
     thing.meth = function(){this.meth.apply(self)}; 
     // thing.meth() is called somewhere within thing; 
    }, 
    meth: function() { 
     alert(this.a); 
    } 
} 
1

既然你無法控制它怎麼叫,你可以試試這個:

var MyPrototype = function() { this.init(); } 
$.extend(MyPrototype.prototype, { 
    a: 5, 
    init: function() { 
     var thing = new SomeOtherClass(); 

     // Create an aliad for this 
     var that = this; 
     thing.meth = function() { 
      // You can always access the object using it's "that" alias 
      alert(that.a); 
     }; 
    } 
} 

或者......

var MyPrototype = function() { this.init(); } 
$.extend(MyPrototype.prototype, { 
    a: 5, 
    init: function() { 
     var thing = new SomeOtherClass(); 

     // Create an aliad for this 
     var that = this; 
     thing.meth = function() { 
      // You can always access the object using it's "that" alias 
      that.meth(); 
     }; 
    }, 
    meth: { 
     alert(this.a); 
    } 
} 
0

您的代碼示例開始前,加入這一行:

var self = this; 

然後更換的「這個」與「自我」你的代碼所有用途。

(我想了一堆答案,這樣的說的或多或少同樣的事情。)