bind 方法 (Function) (JavaScript)

转自:http://msdn.microsoft.com/zh-cn/library/ff841995

对于给定函数,创建具有与原始函数相同的主体的绑定函数。 在绑定功能中,this 对象解析为传入的对象。 该绑定函数具有指定的初始参数。

function.bind(thisArg[,arg1[,arg2[,argN]]])

参数

function

必选。 一个函数对象。

thisArg

必选。 可在新函数中为其引用 this 关键字的对象。

arg1[,arg2[,argN]]]

可选。 要传递到新函数的参数的列表

 

返回值

与 function 函数相同的新函数,thisArg 对象和初始参数除外。

 

异常

如果指定的 function 不是函数,则将引发 TypeError 异常。

 

举例

下面的代码演示如何使用 bind 方法。

 1 // Define the original function.
 2 var checkNumericRange = function (value) {
 3     if (typeof value !== 'number')
 4         return false;
 5     else
 6         return value >= this.minimum && value <= this.maximum;
 7 }
 8 
 9 // The range object will become the this value in the callback function.
10 var range = { minimum: 10, maximum: 20 };
11 
12 // Bind the checkNumericRange function.
13 var boundCheckNumericRange = checkNumericRange.bind(range);
14 
15 // Use the new function to check whether 12 is in the numeric range.
16 var result = boundCheckNumericRange (12);
17 console.log(result); // true
18 
19 

 

在下面的示例中,thisArg 对象与包含原始方法的对象不同。

 1 // Create an object that contains the original function.
 2 var originalObject = {
 3     minimum: 50,
 4     maximum: 100,
 5     checkNumericRange: function (value) {
 6         if (typeof value !== 'number')
 7             return false;
 8         else
 9             return value >= this.minimum && value <= this.maximum;
10     }
11 }
12 
13 // Check whether 10 is in the numeric range.
14 var result = originalObject.checkNumericRange(10);
15 console.log(result + " "); // false
16 
17 
18 // The range object supplies the range for the bound function.
19 var range = { minimum: 10, maximum: 20 };
20 
21 // Create a new version of the checkNumericRange function that uses range.
22 var boundObjectWithRange = originalObject.checkNumericRange.bind(range);
23 
24 // Check whether 10 is in the numeric range.
25 var result = boundObjectWithRange(10);
26 console.log(result); // true
27

 

以下代码演示如何使用 arg1[,arg2[,argN]]] 参数。 该绑定函数将 bind 方法中指定的参数用作第一个参数和第二个参数。 在调用该绑定函数时,指定的任何参数将用作第三个、第四个参数(依此类推)。

 1 // Define the original function with four parameters.
 2 var displayArgs = function (val1, val2, val3, val4) {
 3     console.log(val1 + " " + val2 + " " + val3 + " " + val4);
 4 }
 5 
 6 var emptyObject = {};
 7 
 8 // Create a new function that uses the 12 and "a" parameters
 9 // as the first and second parameters.
10 var displayArgs2 = displayArgs.bind(emptyObject, 12, "a");
11 
12 // Call the new function. The "b" and "c" parameters are used
13 // as the third and fourth parameters.
14 displayArgs2("b", "c"); // 12 a b c
15 

 

要求

在以下文档模式中受支持:Internet Explorer 9 标准模式、Internet Explorer 10 标准模式和 Internet Explorer 11 标准模式。此外,也在应用商店应用(Windows 8 和 Windows Phone 8.1)中受支持。请参见版本信息

在以下文档模式中不受支持:Quirks、Internet Explorer 6 标准模式、Internet Explorer 7 标准模式、Internet Explorer 8 标准模式。

 

posted @ 2014-08-26 15:13  johnnylion  阅读(1970)  评论(0编辑  收藏  举报