改变this调用 指向第一个参数
原理:在指向对象里加上这个调用函数这个方法即可
//手写call/apply
Function.prototype.myCall = function(context,...args){
context = context || window;
context.fn = this;
// const result = context.fn(...args)//call
const result = context.fn([...args])//apply
delete context.fn;
return result;
}
const obj1 ={
name:'zhangsan'
}
function fn(){
console.log(this.name);
}
fn.myCall(null,1,2);
fn.myCall(obj1,1,2);
手写bind 返回一个函数,传递多次参数 支持直接调用。new调用(this指向丢失)
//手写bind
Function.prototype.myBind = function(context,...args){
const _this = this;
return function func(...args1){
if(this instanceof func){
return new _this(...args,...args1)
}else{
return _this.call(context,...args,...args1)
}
}
}
const obj2 ={
name:'mybind'
}
function fn(a,b){
console.log(this.name,a,b);
}
const fn1=fn.myBind(obj2,1);
fn1(2)//直接调用
const fn2 = new fn1(2)//作为构造函数等待被调用