一、考察内容
- this指向:this指向是谁调用指向谁,这句符合大部分场景。但是最准确的是this指向最近的调用者。如fun.test.myFun()指向的是text。
- arguments:argument 对象包含了函数调用的参数数组
- bind、call、apply的区别:
- bind与call和apply的区别是bind返回一个函数,调用时不会立即执行。
- call接收参数是分开的,apply接受是以数组的形式
二、手写bind
以代码注释形式讲解
/* 手写bind函数*/
Function.prototype.myBind =function(ctx,...arg){
ctx = ctx||window //若指向的对象不存在,则指向window
ctx.fn = this //当前this是调用myBind方法的函数,也就是改变作用域的函数
return function(){
let args = [...arg,...arguments] //合并返回函数中传入的参数
ctx.fn(...args)
delete ctx.fn //删除作用域中本不存在的fn
}
}
let a = 111
let b = 222
function test(){
console.log(this.a,this.b,...arguments)
}
let mb = test.myBind({
a:4,
b:2
},1)
mb(111)
三、手写call
/* 手写call函数*/
Function.prototype.myCall =function(ctx,...arg){
ctx = ctx||window
ctx.fn = this
ctx.fn(...arg)
delete ctx.fn
}
function test2(){
console.log(this.a,this.b,...arguments)
}
let call = test2.myCall({
a:4,
b:2
},1)
四、手写apply
/* 手写apply函数*/
Function.prototype.myApply =function(ctx,arg){
ctx = ctx||window
ctx.fn = this
ctx.fn(...arg)
delete ctx.fn
}
function test3(){
console.log(this.a,this.b,...arguments)
}
let apply = test3.myApply({
a:4,
b:2
},[1,2,3])
总结:手写这三个函数其实很简单,主要是弄懂这三个函数的应用以及this的指向问题。