Bind函数原理:
bind函数是创建一个新的函数,这个新函数在调用时会将指定的this值和参数传递给原函数。
1. Function.prototype.myBind = function(context, ...args) { ... }
- 给所有函数加上 myBind 方法。
- context 是要绑定的 this。
- ...args 是预先传入的参数(类似柯里化)。
2. const self = this
- this 指向调用 myBind 的原函数(比如 sayHello.myBind(...) 里的 sayHello)。
- 用 self 保存原函数的引用,后面要用。
3. function boundFn(...innerArgs) { ... }
- 返回一个新函数 boundFn,这个函数就是“绑定后的函数”。
- ...innerArgs 是调用新函数时传入的参数。
4. if (this instanceof boundFn) { ... }
- 判断新函数是不是被 new 关键字调用的。
- 如果是 new boundFn(),那么 this 就是 boundFn 的实例,this instanceof boundFn 为 true。
- 这种情况下,应该让原函数以构造函数的方式执行,并且 this 指向新对象。
5. return new self(...args, ...innerArgs)
- 如果用 new 调用,直接用 new 调用原函数 self,并传入所有参数。
- 这样可以保证原函数的原型链和属性都能继承下来。
6. return self.apply(context, [...args, ...innerArgs])
- 如果不是用 new,就用 apply 调用原函数,this 绑定为 context,参数为预设参数和新传入参数的合并。
7. boundFn.prototype = Object.create(self.prototype)
- 让 boundFn 的原型对象指向原函数的原型对象。
- 这样用 new 调用时,实例能继承原函数的原型属性和方法。
8. return boundFn
- 返回新函数 boundFn,实现了 this 绑定和参数预设。
疑问一:
步骤4:判断新函数是否被new操作调用,判断条件:this就是boundFn的实例。
解决疑惑:可以在构造函数直接打印this,其中this就是构造函数的实例
贴入代码
// 简易版
Function.prototype.myBind = function (content, ...args) {
// 存调用myBind函数的this,保存原函数
let self = this
// 返回一个新的函数
let boundFn = function (...innerArgs) {
self.apply(content, args.concat(innerArgs))
}
return boundFn
}
// 完整版
Function.prototype.myBind = function (content, ...args) {
// 存调用myBind函数的this,保存原函数
let self = this
// 返回一个新的函数
let boundFn = function (...innerArgs) {
// 判断是否new调用
if (this instanceof boundFn) {
return new self(...args, ...innerArgs)
}
return self.apply(content, args.concat(innerArgs))
}
boundFn.prototype = Object.create(self.prototype)
return boundFn
}
function Person(name, age) {
this.name = name
this.age = age
// console.log(this.height, name, age)
console.log(this)
console.log(this instanceof Person)
}
let presonObj = {
height: 180
}
let bound = Person.myBind(presonObj, "张三", 18)
// bound()
// 测试new调用
let p = new bound()
console.log(p)