定义:bind 方法返回一个新函数,函数的 this 被 bind 的第一个参数指定,bind 其他的参数将做为新函数的参数待新函数被调用时使用app
if (!Function.prototype.bind){
Function.prototype.bind = function (ctx) {
let arg = Array.prototype.slice.call(arguments, 1);
let self = this;
return function (){
return self.apply(ctx, arg.concat(Array.prototype.slice.call(arguments)));
}
}
}
let module = {
add: function(a, b) {
return a + b;
}
}
let obj = {};
let add = module.add.bind(obj, 1);
console.log(add(2));
复制代码
当使用被 bind 绑定过的构造函数来建立实例时,绑定的 this 会被忽略,表现为和正常实例化对象一致,不过提供的参数列表仍然会插入到构造函数调用时的参数列表以前函数
if (!Function.prototype.bind){
Function.prototype.bind = function (ctx) {
let arg = Array.prototype.slice.call(arguments, 1);
let self = this;
let fBond = function (){
let _this = this instanceof fBond ? this : ctx;
return self.apply(_this, arg.concat(Array.prototype.slice.call(arguments)));
}
if (this.prototype) {
fBond.prototype = this.prototype
}
return fBond;
}
}
复制代码