- 实现
call
函数:
- 明确下Context
- 将当前函数作为Context的一个内置方法
- 然后用上下文的内置方法执行,就把函数的this替换为Context了。
Function.prototype.myCall = function (context, ...args) {
context = context || window;
const fn = Symbol('fn');
context[fn] = this;// 将myCall方法绑定
const result = context[fn](...args);
delete context[fn];
return result;
};
使用
function greet(name) {
console.log(`Hello, ${name}! I'm ${this.name}.`);
}
const person = {
name: 'Alice'
};
greet.myCall(person, 'Bob');
// 输出:Hello, Bob! I'm Alice.
- 实现
apply
函数:
Function.prototype.myApply = function (context, args) {
context = context || window;
const fn = Symbol('fn');
context[fn] = this;
const result = context[fn](...args);
delete context[fn];
return result;
};
使用
function greet(name, age) {
console.log(`Hello, ${name}! I'm ${this.name} and I'm ${age} years old.`);
}
const person = {
name: 'Alice'
};
greet.myApply(person, ['Bob', 25]);
// 输出:Hello, Bob! I'm Alice and I'm 25 years old.
- 实现
bind
函数:
- 返回一个新的函数,通过
self.apply(context
替换掉上下文 - 绑定后是个新的函数,可能有新的参数
Function.prototype.myBind = function (context, ...args) {
const self = this;
return function (...innerArgs) {
return self.apply(context, args.concat(innerArgs));
};
};
使用
function greet(name) {
console.log(`Hello, ${name}! I'm ${this.name}.`);
}
const person = {
name: 'Alice'
};
const boundGreet = greet.myBind(person);
boundGreet('Bob');
// 输出:Hello, Bob! I'm Alice.
原文链接:https://juejin.cn/post/7248995705292292153 作者:总瓢把子