跳到主要内容

call和apply

Function.prototype.myCall = function (context) {
context = context || window;
context.fn = this;
var args = [];
for (var i = 1; i < arguments.length; i++) {
args.push(arguments[i]);
}
const result = context.fn(args);
delete context.fn;
return result;
};
function greet(name) {
console.log('Hello, ' + name);
}
greet.myCall(null, 'Alice'); // Hello, Alice
Function.prototype.myApply = function (context, args) {
// 如果没有传入context,则默认为全局对象
context = context || window;
// 将函数赋值给context的属性
context.fn = this;
// 调用函数,并传入参数
var result;
if (args) {
result = context.fn(args);
} else {
result = context.fn();
}
// 删除刚才添加的属性
delete context.fn;
// 返回结果
return result;
};