相关知识点
- 实现
call 方法
- 实现
apply 方法
- 实现
bind 方法
实现 call 方法
- 首先
context 为可选参数,如果不传的话默认上下文为 window;
- 接下来给
context 创建一个 fn 属性,并将值设置为需要调用的函数;
- 因为
call 可以传入多个参数作为调用函数的参数,所以需要将参数剥离出来;
- 然后调用函数并将对象上的函数删除;
Function.prototype.myCall = function (context) {
if (typeof this !== "function") {
throw new Error("Error");
}
context = context || window;
context.fn = this;
const args = Array.from(arguments).slice(1);
context.fn(...args);
delete context.fn;
};
function print(age) {
console.log(this);
console.log(this.name, age);
}
var obj = {
name: "jack"
};
print.myCall(obj, 1, 2, 3);
print.myCall(obj, [1, 2, 3]);
实现 apply 方法
Function.prototype.myApply = function (context) {
if (typeof this !== "function") {
throw new TypeError("Error");
}
context = context || window;
context.fn = this;
if (arguments[1]) {
if (Object.prototype.toString.call(arguments[1]) === "[object Array]") {
context.fn(arguments[1]);
} else {
throw new TypeError("参数只能为数组");
}
} else {
context.fn();
}
delete context.fn;
};
function print(age) {
console.log(this.name, age);
}
var obj = {
name: "jack"
};
print.myApply(obj, [10, 20, 30]);
print.myApply(obj);
实现 bind 方法
Function.prototype.myBind = function (context) {
if (typeof this !== "function") {
throw new TypeError("Error");
}
const _this = this;
context = context || window;
const args = [...arguments].slice(1);
return function () {
return _this.apply(context, args.concat(...arguments));
};
};
function print(args) {
console.log(this.name, args);
}
var obj = {
name: "Tom"
};
let fn = print.myBind(obj, [1, 3, 5]);
let fn2 = print.myBind(obj, 2, 4, 6);
fn();
fn2();