别人写的call的实现(xiuyan)
Function.prototype.myCall = function(context, ...args){
// 把函数挂到目标对象上
context.func = this;
// 执行函数
context.func(...args);
// 删除目标对象上的函数
delete context.func;
}
var showName = function(surname, middlename){
console.log(this.name+‘ ‘+surname+‘ ‘+middlename);
}
var me = {
name:‘lizzy‘
}
showName.myCall(me, ‘young‘,‘hh‘)
自己来实现一个apply
Function.prototype.myApply = function(context, args){
context.func = this;
context.func(args);
delete context.func;
}
自己来实现一个bind
Function.prototype.myBind = function(context){
const fn = this;
const args = Array.prototype.slice.call(arguments,1)
if (context){
context.fn = fn;
// 这里是最终调用的地方,会传来第二次参数
var result = function(...args2){
context.fn(...[...args, ...args2]);
delete context.fn;
}
} else {
var result = function(...args){
fn(...[...args, ...args2]);
}
}
return result;
}
var showName = function(...args){
console.log(this.name, ...args)
}
var me = {
name:‘lizzy‘
}
var you = {
name:‘zzjwd‘,
showName: showName.myBind(me,‘name2‘)
}
you.showName(‘name3‘) //lizzy name2 name3
call, apply, bind改变this指向及实现