javascript的bind方法绑定深入理解
一.方法介绍
function.bind(thisArg[,arg1[,arg2[,argN]]])
1.方法绑定在thisArg对象上。
2.可以绑定参数,用于返回值方法的下一步参数
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);
带有参数的绑定:
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");
二.深入理解bind方法
html
<div id="my-btn">button</div>
var btn = document.getElementById("my-btn");
btn.addEventListener("click", handler.handleClick, false);
btn.addEventListener("click", function()//ie9以下中修改为attachEvent
{
handler.handleClick();
}, false);
btn.addEventListener("click", (function()
{
return function(){handler.handleClick();}
})(), false);
btn.addEventListener("click", handler.handleClick.bind(handler), false);//js原生bind作用
三.bind的自定义方法,兼容所有浏览器
Function.prototype.bind = function (context) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
return function () {
alert("Function.prototype.bind");
return self.apply(context, args.concat(Array.prototype.slice.call(arguments, 0)));
};
}
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");
完
浙公网安备 33010602011771号