JS实现call,apply,bind函数
实现之前的预备知识
- ...用作展开
- ...用作剩余参数
- Object.create()的作用
- 原型链与构造函数
这些有时间补上吧
call函数实现
Function.prototype.myCall = function (obj, ...args) {
obj = obj || window;
obj.fn = this;
let result = obj.fn(...args);
delete obj.fn;
return result;
};
apply函数实现
Function.prototype.myApply = function (obj) {
let context = obj || window;
let result;
context.fn = this;
if (arguments[1]) {
result = context.fn();
} else {
result = context.fn(...arguments[1]);
}
delete context.fn;
return result;
};
bind函数实现
Function.prototype.mbind = function (obj, ...args) {
let self = this;
let bound = function () {
self.apply(obj,args);
};
bound.prototype = Object.create(self.prototype, {
constructor: {
value: self,
},
});
return bound;
};
如有错误还请指正

浙公网安备 33010602011771号