手写js中改变this的三种方法
2021-11-24 本文已影响0人
_静夜听雨_
在es6之前,我们经常遇到需要手动改变this指向的问题,call? apply?bind?,三者有啥区别,搞懂原理,也就清晰了。
call
Function.prototype.my_call = function(obj, ...args){
obj = obj || window;
const fn = Symbol();// Symbol防止重名key
obj[fn] = this;
return obj[fn](...args);// 执行,返回执行值
}
apply
Function.prototype.my_apply = function(obj, args){
obj = obj || window;
const fn = Symbol();// Symbol防止重名key
obj[fn] = this;
return obj[fn](...args);// 执行,返回执行值
}
bind
Function.prototype.my_bind = function(obj, ...args){
obj = obj || window;
const fn = Symbol();// Symbol防止重名key
obj[fn] = this;
const _this = this;//保存this
const res = function(...args1){
if(this instanceof _this){
this[fn] = _this;
this[fn](...[...args, ...args1]);
delete this[fn];
}else{
this[fn](...[...args, ...args1]);
delete this[fn];
}
}
res.prototype = Object.create(this.prototype);
return res;
}