天天看點

js 手動實作call、apply、bind實作call實作apply實作bind

實作call

Function.prototype._call = function (obj, ...args) {
    if (!(typeof this == "function" && typeof obj == "object")) {
        return;
    }
    obj.fn = this;
    if (args && args.length > 0) {
        return obj.fn(...args);
    } else {
        return obj.fn();
    }
}
           

實作apply

Function.prototype._apply = function (obj, args) {
    if (!(typeof this == "function" && typeof obj == "object")) {
        return;
    }
    obj.fn = this;
    if (args && args.length > 0) {
        return obj.fn(...args);
    } else {
        return obj.fn();
    }
}
           

實作bind

Function.prototype._bind = function () {
    if (!(typeof this == "function" && arguments.length > 0)) {
        return;
    }
    var self = this; //儲存原函數
    var context = [].shift.call(arguments); //儲存需要綁定的this上下文
    var args = [].slice.call(arguments); //将剩餘參數轉化為數組
    return function () {
        self.apply(context, [].concat.call(args, [].slice.call(arguments)));
    }
}
           

繼續閱讀