實現call()方法
Function.prototype.mycall = (context,...args) {
// 判斷this是否函數,否返回typeerror
if (typeof this !== 'function') {
throw new TypeError('不是函數');
}
context = context || window;
context.fn = this;
const res = context.fn(...args);
delete context.fn;
return res;
}
實現apply()
Function.prototype.myapply = (context,...args) => {
if (typeof this !== 'function') {
throw new TypeError('不是函數');
}
context = context || window;
context.fn = this;
args = args && args[0] || [];
const res = context.fn(...args);
delete context.fn;
return res;
}
實現bind()
Function.prototype.mybind = (context,...args) => {
if (typeof this !== 'function') {
throw new TypeError('不是函數');
}
let fn = this;
const bind = (...args2) => {
return fn.apply(this instanceof bind?context:context,[...args,...args2]);
}
bind.prototype = Object.create(this.prototype);
return bind;
}