js 实现 call()

// 在函数参数中   ...argArray 是 把多个传值参数组成一个 数组,同时在函数内拿到 argArray是一个数组了 ,
// 如果值 是一个数组时,arr=[1,2,3]; ...arr 的值是 1,2,3,
// 如果值 不是数组时, ...arr 的值是  [1,2,3]


Function.prototype.hyCall = function(thisArg, ...argArray) {
    // 在函数中thisArg 必须是Object类型,arrArry组成数组类型搜集参数

    // 1.获取到真实需要调用的函数:获取当前this指向
    var fn = this;

    // 2.绑定this,不存在 指向 window
    //@param thisArg — An object to which the this keyword can refer inside the new function.
    // 在apply(),call(),bind()中this绑定值如果是 null 或 undefined 时 ,this 指向 window,
    thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window;
    thisArg.fn = fn;
    // 判断传值是否为存在
    var newArray = argArray || [];
    var result = thisArg.fn(...newArray);
    delete thisArg.fn;
    return result;
};

function foo(num1, num2) {
    console.log(this);
    return num1 + num2;
}

var result1 = foo.hyCall('obj', 10, 2); // 隐式调用 this指向 foo
console.log(result1);
var result2 = foo.hyCall('obj'); // 隐式调用 this指向 foo
console.log(result2);

var result = foo.call('obj', 10, 20);
console.log(result);

//输出打印结果
// { [String: 'obj'] fn: [Function: foo] }
// 12
// { [String: 'obj'] fn: [Function: foo] }
// NaN
// [String: 'obj']
// 30
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容