Function.prototype.bind = function(context) {
var self = this; // 保存原函数
return function() { // 返回一个新函数
return self.apply(context, arguments); // 执行新函数时,将传入的上下文context作为新函数的this
}
}
Function.prototype.bind(thisArg[, arg1[, arg2[, ...]]])
var A = function(name) {
this.name = name;
}
var B = function() {
A.bind(this, arguments);
}
B.prototype.getName = function() {
return this.name;
}
var b = new B("hello");
console.log(b.getName()); // "hello"
var paint = {
color: "red",
count: 0,
updateCount: function() {
this.count++;
console.log(this.count);
}
};
// 事件处理函数绑定的错误方法:
document.querySelector('button')
.addEventListener('click', paint.updateCount); // paint.updateCount函数的this指向变成了该DOM对象
// 事件处理函数绑定的正确方法:
document.querySelector('button')
.addEventListener('click', paint.updateCount.bind(paint)); // paint.updateCount函数的this指向变成了paint
var notify = {
text: "Hello World!",
beforeRender: function() {
alert(this.text);
},
render: function() {
// 错误方法:
setTimeout(this.beforeRender, 0); // undefined
// 正确方法:
setTimeout(this.beforeRender.bind(this), 0); // "Hello World!"
}
};
notify.render();
var a = {};
Array.prototype.push.bind(a, "hello", "world")();
console.log(a); // "hello", "world"
if (!Function.prototype.bind) {
Function.prototype.bind = function() {
var self = this, // 保存原函数
context = [].shift.call(arguments), // 需要绑定的this上下文
args = [].slice.call(arguments); // 剩余的参数转成数组
return function() { // 返回一个新函数
// 执行新函数时,将传入的上下文context作为新函数的this
// 并且组合两次分别传入的参数,作为新函数的参数
return self.apply(context, [].concat.call(args, [].slice.call(arguments)));
}
};
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有