1、call函数
Function.prototype.myCall = function (context) {
if (typeof this != "function") {
throw new Error("error")
}
context = context || window;
context.fn = this;
var args = [...arguments].slice(1);
var result = context.fn(...args);
delete context.fn;
return result;
}
使用
var obj = {
a: 23,
b: 12,
}
function fa() {
return this.a + this.b
}
var res = fa.myCall(obj)
2、apply函数
apply函数与call函数的区别是接受参数的形式不一样,apply接收参数为数组。
Function.prototype.myApply = function (context) {
if (typeof this != "function") {
throw new Error("error")
}
context = context || window;
context.fn = this;
let result;
if (arguments[1]) {
result = context.fn(...arguments[1])
} else {
result = context.fn()
}
delete context.fn;
return result;
}
3、bind函数
Function.prototype.myBind = function (context) {
if (typeof this != "function") {
throw new Error("error")
}
const _this = this;
const args = [...arguments].slice(1);
return function F() {
if (this instanceof F) {
return new _this(...args, ...arguments)
} else {
return _this.apply(context, args.concat(...arguments))
}
}
}