Function.prototype.myCall = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context || window;
// 在调用对象上设置一个新的方法fn,这个fn指向被调用方法
context.fn = this;
let args = [...arguments].slice(1);
// 由context上的fn方法执行参数
let result = context.fn(...args);
delete context.fn;
return result
};
Function.prototype.myApply = function(context) {
if (typeof this !== 'function') {
throw new TypeError('Error')
}
context = context || window;
context.fn = this;
let result;
if (arguments[1]) {
result = context.fn(...arguments)
} else {
result = context.fn
}
return result
};
Function.prototype.myBind = function(context) {
let self = this;
// self就是被调用方法
let args = [...arguments].slice(1);
return function newFn() {
let newArgs = [...arguments];
// this指的是返回函数的调用对象
// 如果该调用对象的原型链上存在newFn
// 则说明调用了new方法
if (this instanceof newFn) {
return new self(...args.concat(newArgs))
};
return self.apply(context, args.concat(newArgs))
}
// bind有两种调用方法一种是new一种是直接调用
// bind函数支持函数柯里化
}
apply,call,bind
最新推荐文章于 2025-07-15 11:29:13 发布
256

被折叠的 条评论
为什么被折叠?



