apply源码中是用C++实现的,我们使用Javascript模拟
1、apply自定义实现
Function.prototype.nsapply = function (thisArg, args) {
var fn = this;
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window;
thisArg.fn = fn;
args = args ? args : [];
var result = thisArg.fn(...args);
delete thisArg.fn;
return result;
};
function sum(num1, num2) {
console.log("sum函数被调用", num1, num2);
return num1 + num2;
}
var result = sum.nsapply("abc", [10, 20, 30, 40]);
console.log(result);
2、bind自定义实现
Function.prototype.nsbind = function (thisArg, ...args) {
var fn = this;
thisArg =
thisArg !== null && thisArg !== undefined ? Object(thisArg) : window;
function proxyFn(...params) {
thisArg.fn = fn;
var finalArgs = [...args, ...params];
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(num1, num2, num3, num4);
}
var bar = foo.nsbind("abc");
var result = bar();
console.log(result);
var newSum = sum.nsbind("abc", 12, 23);
var result1 = newSum(30, 40);
|