bind
function sum(a,b,c) {
return a-b+c
}
let sum1 = sum.bind(null,1,3)
console.log(sum1(6));//6
let sum2 = sum.bind(null,1)
console.log(sum1(6,3));//6
bind后只有一次传参机会机会,不可以 sum2(6)//NaN
手写bind 难点
// 判断是否把bind返回的当做有一个构造函数,使用new操作符
// let person =new Person.bind(obj)()
// Person.bind(obj)执行返回 F
// 执行 new F()
let funobj = function () {
this.age = 18;
return {
a:4
}
}
let b = new funobj()
console.log(b);//{a: 4}
Function.prototype.bind1 = function(context, ...args1){
// 防止Function.prototype.bind()的方式调用
if(this === Function.prototype){
throw new TypeError('Error')
}
// this指向的是当前的函数
const _this = this
// 返回的是一个函数,而我们在函数中也可以传递参数,并且我们的参数会进行合并
// 例如args1.concat(args2)
return function F(...args2){
console.log(_this)//闭包
console.log(this)//window
// 判断是否把bind返回的当做有一个构造函数,使用new操作符
// let person =new Person.bind(obj)()
// Person.bind(obj)执行返回 F
// 执行 new F()
// 我们的构造函数的调用和普通函数的调用时有区别的
// new Person() 和 Person()是有区别的
// 如果是这样的话,那就返回new Person
if(this instanceof F){
// _this 就是我们调用的构造函数的实例,所以我们返回的是new操作的实例
return new _this(...args1,...args2)
}
// 如果不是,就直接返回一个函数调用结果
// a.bind(context)()
// 进行分解a.bind返回的是F函数
// 之后我们在进行调用函数,并且把传入的上下文作为调用的上下文
return _this.apply(context, args1.concat(args2))
}
}