bind use
func.bind(thisArg[, arg1[, arg2[, …]]])
thisArg改变目标函数this指向的值,若为基本类型将转化为基本类型对应的包装对象
当函数直接调用
// bind使用
function func(...arg){
console.log(this)
console.log(arg)
}
func.prototype.fn = function(){
console.log('fn')
}
let newFunc = func.bind([1,2,3],1,2,3,4,5)
// let newFunc = func.bind(1,1,2,3,4,5)
newFunc()
当构造函数使用
let f = new newFunc()
console.log(f)
模拟写一个bind方法
// ES5版本
Function.prototype.customBindES5 = function(context){
// 目标函数
let _this = this
let arg = Array.prototype.slice.call(arguments,1) // 转数组
// let arg = Array.from(arguments)
// let arg = [ ...arguments ]
// 返回新函数
return function(){
let newArg = Array.prototype.slice.call(arguments, 0)
// let newArg = Array.from(arguments)
// let newArg = [ ...arguments ]
return _this.apply(context, arg.concat(newArg))
}
}
// 初始版本 v1
Function.prototype.customBind = function(context, ...rest){
// 目标函数
let _this = this
let arg = rest
// 返回新函数
return function(...rest){
let newArg = rest
return _this.apply(context, [ ...arg, ...newArg ])
}
}
/*
目标函数:调用bind的函数,func.bind func就称之为是目标函数
新函数:bind返回的函数,let newFunc = func.bind() newFunc就称之为新函数
*/
/*
1. 返回的函数作为构造函数,新函数要继承目标函数的原型
2. 一旦把新函数当成构造函数了,目标函数的this应该指向实例对象
*/
// 考虑到原型链 v2
Function.prototype.customBind = function(context, ...rest){
// // 目标函数
let _this = this
let arg = rest
let Bound = function(...rest){
let newArg = rest
// 如果这个函数作为了构造函数,那么目标函数的this,应该执行的是实例对象
// 如果这个不是作为构造函数,目标函数中的this还指向context
// console.log(this,this instanceof Bound,11)
let thisArgSelf = this instanceof Bound ? this : context
_this.apply(thisArgSelf, [ ...arg, ...newArg ])
}
// Object.create 用来创建以某一个对象作为原型的对象的
Bound.prototype = Object.create( this.prototype )
Bound.prototype.constructor = this
// 返回新函数
return Bound
}
function fn(...arg){
console.log(this)
console.log(arg)
}
fn.prototype.run = function(){}
let newFn = fn.customBind({a:1}, 1, 2, 3)
newFn(4,5,6)
// new newFn(4,5,6)