1、this call apply bind
一個(gè)例子理解 call apply bind 都是為了改變this指向的問題
function sayHello(para){
console.log(`${para} ${this.name}`)
}
person={
name:'zdq'
}
sayHello.call(person,'hello','world')
sayHello.apply(person,['hi'])
const newSayHello= sayHello.bind(person)
newSayHello('hh')
自定義call
Function.prototype.myCall=function(context){
const fn =this;
context.fn=fn
const args = Array.from(arguments).slice(1);
const result= context.fn(...args)
delete context.fn
return result
}
sayHello.myCall(person,'自定義call')
//自定義實(shí)現(xiàn)一個(gè)apply
Function.prototype.myApply=function(context,args){
console.log('myApply',args)
const fn =this;
context.fn=fn
const result=context.fn(...args)
delete context.fn
return result
}
//手寫bind函數(shù)
Function.prototype.myBind=function(context){
const fn=this;
console.log('myBind',arguments)
let args = Array.from(arguments).slice(1); //
console.log('myBind',args)
return function(){
const newArr=args.concat(Array.from(arguments))
fn.apply(context,newArr)
console.log('myBind newArr',newArr)
// fn.apply(context,args)
}
}
// 聲明一個(gè)函數(shù)
function fn(a, b, c) {
console.log("函數(shù)內(nèi)部this指向:", this);
console.log("參數(shù)列表:", a, b, c);
}
const newFun=fn.myBind({},10,20,30)
newFun(40)