2016-01-17 27 views
0

因此,閱讀和在這本優秀的書的Javascript忍者進步。儘管如此,下面的代碼仍然存在問題,我無法理解爲什麼使用cb.call的情況,以及爲什麼看起來是空的上下文正在通過。我認爲它可能剛剛完成了cb(this [i],i,this),因爲'this'沒有被使用。我在這裏錯過了一個重要的觀點嗎?請幫忙。謝謝。JavaScript忍者書與回調示例

<ul id="results"></ul> 
<script> 
    function assert(val,desc){ 
    var li = document.createElement("li"); 
li.className = val ? "pass" : "fail"; 
li.appendChild(document.createTextNode(desc)); 
document.getElementById("results").appendChild(li); 

    } 

    if (!Array.prototype.forEach2) { 
    Array.prototype.forEach2 = function(cb,context){ 
    for (var i = 0; i < this.length; i++){ 
     cb.call(context ||null, this[i], i, this); 
    } 
}; 
    } 

    ["a,","b","c"].forEach2(function(value,index,array){ 
    assert(value,"Is in position " + index + " out of " + (array.length - 1));   
    }); 

    assert(true,"this will be green"); 
    assert(false,"this is RED"); 
</script> 

回答

1

在爲forEach2具體的例子列出了您的權利,上下文(this)不被使用,所以你可以只是做在執行普通函數調用。如果你不在意在你的回調函數中具有this的具體值,那麼你可以在這裏停下來,只是使用常規函數調用。

但是,使用.call和允許上下文傳遞執行給你傳遞一個特定的上下文值如果您需要它在某些時候的選項,但是不要求你通過它,如果你不需要它。意思是,你可以這樣做:

var context = { 
    something: 'hello' 
}; 

['a', 'b', 'c'].forEach2(function(value, index, array) { 
    // this.something would be 'hello' in this function 
}, context); 
+0

謝謝你,並接受 – user3502374