2016-03-11 43 views
0

bind()函數的一些解釋,我看到的源代碼在MSD提供有關在JavaScript

// Define the original function with four parameters. 
var displayArgs = function (val1, val2, val3, val4) { 
    document.write(val1 + " " + val2 + " " + val3 + " " + val4); 
} 

var emptyObject = {}; 

// Create a new function that uses the 12 and "a" parameters 
// as the first and second parameters. 
var displayArgs2 = displayArgs.bind(emptyObject, 12, "a"); 

// Call the new function. The "b" and "c" parameters are used 
// as the third and fourth parameters. 
displayArgs2("b", "c"); 

// Output: 12 a b c 

我不明白這是如何的源代碼工作。綁定功能可以自動映射參數?在這裏,它第二次綁定兩個參數。

+3

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind綁定可以有多個參數。第一個參數將被用作'this'的值,並且當該函數被調用時,其餘參數將作爲參數傳入 – blessenm

回答

1

第一個參數始終是您想要傳遞的this值,其餘參數是您函數的參數。您可以部分傳遞這些參數。

這意味着如果您現在有部分參數,並且想要在稍後可用時傳遞其餘參數,則可以通過使用this綁定函數來實現。

HTH。

相關問題