首先call的功能:1.调用被绑定函数2.传入this指向,被绑定函数this指向设置内容.3.可以传入参数
第一步:为所有函数设置一个hycall方法,为了知道是哪一个函数调用的hycall,所以用了this(最后一行其实就是隐式绑定,此时this就是调用的函数)。后面的思路就是直接调用这个函数就可以。但是有一些需要考虑的事情。
Function.prototype.hycall = function(thisArg, ...args){
var fn = this;
var result = fn(...args);
return result;
}
function foo() {
console.log("foo执行");
}
function sum(num1, num2) {
console.log("sum执行", num1, num2);
return num1 + num2;
}
sum.hycall({},1,3);
第二步,考虑this指向。第一步用fn(...args)方法调用需使用的参数例如sum,此时this并没有传入函数this是全局GO。解决这个问题只需要改变fn的调用方式,所以用了加属性的方法。但是多了个属性给他delete掉。
Function.prototype.hycall = function(thisArg, ...args){
var fn = this;
thisArg.fn = fn;
var result = thisArg.fn(...args);
delete thisArg.fn;
return result;
}
function foo() {
console.log("foo执行")
console.log('this是' + this);
}
function sum(num1, num2) {
console.log("sum执行", num1, num2)
return num1 + num2
}
foo.hycall('调用hycall',1,3);
第三步:考虑thisArg传入的是非对象类型,加一行: thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg): window。最终:
Function.prototype.hycall = 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执行")
console.log('this是' + this);
}
function sum(num1, num2) {
console.log("sum执行", num1, num2)
return num1 + num2
}
foo.hycall('调用hycall',1,3);