2015-12-18 26 views
0

首先:我不知道如何調用everyting,因爲我對於編寫javascript的OOP方式比較陌生,所以我會盡力解釋爲什麼儘可能好。我的問題是我想訪問一個對象內部的屬性(所以我可以使用this關鍵字。只要我在對象的範圍內,這可以正常工作。當我超出範圍時,我會喜歡,而我不能使用this -keyword再訪問這些屬性
我的代碼:在jQuery函數和其他方法中使用父對象的屬性

var Octa = Octa || function() { 
    this._initialize(); 
}; 

Octa.prototype = { 
     string: 'Foo', 

     _initialize: function() { 
      console.log(this.string); //Output: "Foo" 
      this.othermethod(); 
     } 
} 

var Octa = new Octa(); 

但是,當我有一個Octa方法中的一個方法,所以範圍之外,我無法使用this瞭解Octa的房源,我無法抵達Octa的房源。
例如:

othermethod: function() { 
    $.ajax({ 
     url: this.globalUrl + 'content/language/lang.' + l + '.php', 
     data: { 
      ajax: true 
     }, 
     dataType: 'json', 
     success: function (response) { 
      Octa.lang = response; 
     } 
    }); 
    console.log(JSON.stringify(this.lang)); //Output: null, which means Octa.lang wasn't reachable in the ajax success event (the ajax request was successful). 
} 

有沒有達到Octa其他物體內範圍的方法嗎?或者在jQuery回調中,因爲同樣的問題發生在那裏。
我希望我的問題是可以理解的,如果沒有,我會盡量給予更多的澄清。

+0

可能的重複[如何返回來自異步調用的響應?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-調用) – Grundy

+0

$ .ajax只是一個例子。無論我使用什麼,當我走出Octa的界限時,我都無法達到它。但我會讀其他帖子。謝謝! – Galago

+0

_ $。ajax僅僅是一個例子_我建議你刪除'$ .ajax',因爲在第一眼看問題適合作爲愚蠢的關閉。 – Satpal

回答

0

簡單地指回this功能範圍內:

..., 
someMethod: function() { 
    var self = this, 
     ajaxOptions = this.settings.ajaxOptions; 

    // note we can still refer to 'this' at this level 
    $.ajax(ajaxOptions).done(this.ajaxDone).fail(this.ajaxFail); 

    // the function scope changes for the deffered handlers so you can access by reference of 'this' => self 
    $.ajax(ajaxOptions).done(function(data, status, xhr){ 
     self.ajaxDone(data, status, xhr) 
    }).fail(function(xhr, status, error){ 
     self.ajaxFail(xhr, status, error); 
    }); 
}, 
ajaxDone: function(data, status, xhr) {}, 
ajaxFail: function(xhr, status, error) {}, 
... 

希望這是有道理的。

現在也有一個.bind()功能可用於功能範圍綁定到一個參數:

$.ajax(ajaxOptions).done(function(){ 
    this.ajaxDone(); 
}.bind(this)); 

你必須使用填充工具以支持舊版瀏覽器。它更容易使用var self恕我直言。

+0

因爲我不知道bind()方法,它可能在將來非常有用,所以我給你回答我的問題的信用。 – Galago

相關問題