前言
call()方法是使用一个指定this值和单独给出的一个或多个参数来调用函数,本文就是手写call方法
一、call函数的实现步骤
- 判断调用对象是否为函数
- 判断传入上下文对象是否存在,如果不存在,则设置为window
- 处理传入的参数,截取第一个参数后的所有参数
- 将函数作为上下文对象的一个属性
- 使用上下文对象来调用这个方法,并保存返回结果
- 删除刚才新增的属性
- 返回结果
二、call函数实现
1.call函数
代码如下(示例):
Function.prototype.myCall = function (context) {
if (typeof this !== 'function') {
console.error('type error')
return
}
let args = [...arguments].slice(1),
result = null
context = context || window
context.fn = this
result = context.fn(...args)
delete context.fn
return result
}
2.test
代码如下(示例):
//(1)
const obj = {
count: 10,
};
function fn (x, y, z) {
return this.count + x + y + z;
}
let b = fn.myCall(obj, 1, 2, 3); // 执行函数 fn,返回 16
console.log(b)
//(2)
function Product (name, price) {
this.name = name;
this.price = price;
}
function Food (name, price) {
Product.myCall(this, name, price);
this.category = 'food';
}
function Toy (name, price) {
Product.myCall(this, name, price);
this.category = 'toy';
}
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
console.log(cheese)
console.log(fun)
总结
以上就是call函数的实现,该方法的语法和作用与 apply() 方法类似,只有一个区别,就是 call() 方法接受的是一个参数列表,而 apply() 方法接受的是一个包含多个参数的数组。