我試圖在JavaScript中編寫一些OOP,我偶然發現了一個問題,我確定我後來會在代碼中使用它,並希望現在處理它。如何在不使用javascript或javascript的情況下在函數內部訪問此函數?
例如利用這個代碼:
var FeedClass = function(){
this.init = function(){
this.loadItems();
},
this.loadItems = function(){
var that = this; // heres my problem
function inner(){
that.startLoading();
}
inner();
},
this.startLoading = function(){
alert("started Loading");
}
this.init();
};
var feed = new FeedClass();
問題,我要去使用了大量的內部函數,將調用"this"
,我的代碼將是混亂,如果我繼續寫var that = this
每一個範圍內。有我可以使用的另一種模式或解決方法嗎?
您應該檢查javascript中的[Function.bind()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)方法。它可能會回答你的問題 – Jhecht
@Jhecht謝謝,你能否給我一個在上面的代碼中使用'bind()'的例子,所以我可以看到它是如何工作的。 – Unknown