2014-06-22 31 views
1

我試圖在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每一個範圍內。有我可以使用的另一種模式或解決方法嗎?

+2

您應該檢查javascript中的[Function.bind()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)方法。它可能會回答你的問題 – Jhecht

+0

@Jhecht謝謝,你能否給我一個在上面的代碼中使用'bind()'的例子,所以我可以看到它是如何工作的。 – Unknown

回答

2

可以使用call method設置上下文的功能:

this.loadItems = function(){ 
    function inner(){ 
     this.startLoading(); 
    } 
    inner.call(this); 
}, 

apply method作品相似,所不同的是你如何在指定的調用參數。

您也可以使用bind method來設置函數的上下文。這允許你綁定上下文的功能和傳遞稍後調用的函數參考:

this.loadItems = function(){ 
    function inner(){ 
     this.startLoading(); 
    } 
    var i = inner.bind(this); 
    i(); 
}, 

注:bind方法不是在IE 8或更早版本的支持。

+0

完美,正是我想聽到的。 – Unknown

+0

這與('**有效**)與'.bind'完全相同(如果您希望我可以做出答案來向您展示一些差異。 – Jhecht

相關問題