[JavaScript] bind 方法 (Function)
对于给定函数,创建具有与原始函数相同的主体的绑定函数。 在绑定函数中,this 对象将解析为传入的对象。 绑定函数具有指定的初始参数。
function.bind(thisArg[,arg1[,arg2[,argN]]])
下面的代码演示如何使用 bind 方法。
// Define the original function. var checkNumericRange = function (value) { if (typeof value !== 'number') return false; else return value >= this.minimum && value <= this.maximum; } // The range object will become the this value in the callback function. var range = { minimum: 10, maximum: 20 }; // Bind the checkNumericRange function. var boundCheckNumericRange = checkNumericRange.bind(range); // Use the new function to check whether 12 is in the numeric range. var result = boundCheckNumericRange (12); document.write(result); // Output: true
在下面的示例中,thisArg 对象与包含原始方法的对象不同。
// Create an object that contains the original function. var originalObject = { minimum: 50, maximum: 100, checkNumericRange: function (value) { if (typeof value !== 'number') return false; else return value >= this.minimum && value <= this.maximum; } } // Check whether 10 is in the numeric range. var result = originalObject.checkNumericRange(10); document.write(result + " "); // Output: false // The range object supplies the range for the bound function. var range = { minimum: 10, maximum: 20 }; // Create a new version of the checkNumericRange function that uses range. var boundObjectWithRange = originalObject.checkNumericRange.bind(range); // Check whether 10 is in the numeric range. var result = boundObjectWithRange(10); document.write(result); // Output: true
以下代码演示如何使用 arg1[,arg2[,argN]]] 参数。 绑定函数将 bind 方法中指定的参数用作第一个参数和第二个参数。 在调用绑定函数时指定的任何参数将用作第三个、第四个参数(依此类推)。
// 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