您的位置:首页 > Web前端 > JQuery

Javascript bind 与 jQuery bind

2015-07-28 09:08 561 查看

Javascript bind 与 jQuery bind

jQuery bind

- bind() 方法为被选元素添加一个或多个事件处理程序,并规定事件发生时运行的函数。

- 规定向被选元素添加的一个或多个事件处理程序,以及当事件发生时运行的函数。

$("button").bind("click",function(){
$("p").slideToggle();
});


Javascript bind

对于给定函数,创建具有与原始函数相同的主体的绑定函数。 在绑定函数中,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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: