Realize apply, call, bind
1. Implement the call function
Function.prototype.hhcall = function (thisArg, ...args) {
var fn = this;
thisArg =
thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;
thisArg.fn = fn;
var result = thisArg.fn(...args);
delete thisArg.fn;
return result;
};
function foo() {
console.log("foo函数被执行", this);
}
function sum(num1, num2) {
console.log("sum函数被执行", this, num1, num2);
return num1 + num2;
}
foo.call(undefined);
var result = sum.call({
}, 20, 30);
console.log("系统调用的结果:", result);
foo.hhcall({
name: "fifih" });
foo.hhcall(undefined);
var result = sum.hhcall("abc", 20, 30);
console.log("hhcall的调用:", result);
2. Implement the apply function
Function.prototype.hhapply = function (thisArg, argArray) {
var fn = this;
thisArg =
thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;
thisArg.fn = fn;
var result;
argArray = argArray || [];
result = thisArg.fn(...argArray);
delete thisArg.fn;
return result;
};
function sum(num1, num2) {
console.log("sum被调用", this, num1, num2);
return num1 + num2;
}
function foo(num) {
return num;
}
function bar() {
console.log("bar函数被执行", this);
}
var result = sum.apply("abc", [20, 30]);
console.log(result);
var result = sum.hhapply("abc", [20, 30]);
console.log(result);
var result2 = foo.hhapply("abc", [20]);
console.log(result2);
bar.hhapply(0);
3. Implement the bind function
Function.prototype.hhbind = function (thisArg, ...argArray) {
var fn = this;
thisArg =
thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;
function proxyFn(...args) {
thisArg.fn = fn;
var finalArgs = [...argArray, ...args];
var result = thisArg.fn(...finalArgs);
delete thisArg.fn;
return result;
}
return proxyFn;
};
function foo() {
console.log("foo被执行", this);
return 20;
}
function sum(num1, num2, num3, num4) {
console.log(this, num1, num2, num3, num4);
return num1 + num2 + num3 + num4;
}
var bar = foo.bind("abc");
bar();
var newSum = sum.bind("aaa", 10, 20, 30, 40);
newSum();
var newSum = sum.bind("aaa");
newSum(10, 20, 30, 40);
var newSum = sum.bind("aaa", 10);
newSum(20, 30, 40);
var bar = foo.hhbind("abc");
var result = bar();
console.log(result);
var newSum = sum.hhbind("abc", 10, 20);
var result = newSum(30, 40);
console.log(result);
4. Supplement: remaining parameters (...args)
function sum(...nums) {
console.log(nums);
}
sum(10);
sum(10, 20);
sum(10, 20, 30);
sum(10, 20, 30, 40, 50);
var names = ["abc", "cba", "nba"];
function foo(name1, name2, name3) {
console.log(name1, name2, name3);
}
foo(...names);