apply,call,bind手写
手写apply、call、bind
确定this 的值
-
全局执行环境
<script>'use strict'console.log('222',this); </script>
严格模式下和非严格模式下都是全局对象 (window)
-
函数内部
'use strict' function inFn() {console.log('inFn',this); }
严格模式下是undefined;非严格模式下是全局对象 (window)
-
对象方法
'use strict' const peason = {name: '小毅',getName:()=>{console.log('getName', this); // windowreturn this.name},setName(name) {console.log('setName', this); // 对用对象peasonthis.name = name} }
严格模式下和非严格模式下结果一样;getName 方法是箭头函数,this是window; setName 方法是普通函数,this 是调用者 peason
手写call 方法
-
在Function 对象上实列上增加myCall 方法
// 定义 myCall方法 Function.prototype.myCall = function () {} // Object.prototype.myCall = function () {}// function add(a, b) {}// 调用 add.myCll({},a,b)
1、Function或者Object 对象上定义myCall方法,调用的时候,可以根据原型链拿到myCall 方法
2、add 方法也可以说是对象, 因为
add instanceof Object
==> true3、根据上文《确定this 的值》 第三点,
在对象方法里面的this是调用者
,所以add.myCall({},a,b) , add 调用myCall ,此时myCall 方法里面的this 为 调用者:add 方法(对象)// 手写call Object.prototype.myCall = function (target, ...rest) {// this为调用者add,把add 方法放在target对象里target.fn = this//再调用target下的fn,此时调用者是target,所以this为targetconst result = target.fn(...rest) delete target.fn return result }const peason = {name: '小毅'} // 调用 add.myCall(peason,1,2)
-
优化,上面一个版本的call ,可能会把target 对象的fn 属性覆盖掉,使用
Object.prototype.myCall = function (target, ...rest) {const key = new Symbol()target = target || {}target[key] = thisconst result = target.fn(...rest)delete target[key]return result }
手写apply 方法
与call 类似,只是apply 接收的参数是数组
Function.prototype.myApply = function (target,rest) {const key = new Symbol()target = target || {}target[key] = thisconst result = target.fn(rest)delete target[key]return result
}
手写bind
bind 函数绑定是,没有执行,所以返回的是一个函数;
myBind 方法内的this 是调用者add 方法
myBind 内return 的是箭头函数,所以this 也是add方法
this.mycall 相当于 add.mycall ,同上文 mycall原理相当
// mybind 方法
Function.prototype.myBind=function (target,...rest){return (...rest2)=>{this.myCall(target,...rest,rest2)}
}// 累加
add(num1,num2,num3,num4){}// add 调用bind
add.myBind(peason,1,2)