// bind 实现
// 1.返回一个函数
// 2.除了第一个this外 后面接收一堆参数
// 3.改变this的函数可以执行new方法
Function.prototype.bindTwo = function(that, ...arg) {
let _this = this;
function bindFn(...arg2) {
// 判断是否执行了 new 方法 this instanceof bindFn;
// 如果没有new this 指向 window
// arg2 有可能在new的时候传入参数
// arg 和 arg2 只是为了接收参数
return _this.call(this instanceof bindFn ? this : that, ...arg, ...arg2)
}
// 加一个中转函数 避免修改
function bindNullFn(){};
// 继承执行函数的原型
bindNullFn.prototype = this.prototype;
bindFn.prototype = new bindNullFn();
return bindFn;
}
var foo = {
value: 1
};
// 第一步 简单实现
// function bar(name) {
// console.log(this.value, `name:${name}`)
// }
// var bindFoo = bar.bind(foo, 2);
// var bindFoo2 = bar.bindTwo(foo, 3);
// bindFoo();
// bindFoo2();
// 第二步 实现 new
function bar(name, age) {
this.habit = 'shopping';
console.log(this.value);
console.log(name);
console.log(age);
}
bar.prototype.friend = 'kevin';
var bindFoo = bar.bind(foo, 'daisy');
var bindFoo2 = bar.bindTwo(foo, 'daisy');
var obj = new bindFoo('18');
var obj2 = new bindFoo2('18');
// undefined
// daisy
// 18
// console.log(obj.habit);
// console.log(obj.friend);
// shopping
// kevin
看了 这个链接的 https://github.com/mqyqingfeng/Blog/issues/12 的bind 实现 自己实现了一个。