手写收集

92 阅读1分钟

new的模拟实现

function objectFactory() {
    var obj = new Object(null),
    Constructor = [].shift.call(arguments);
    // 实例隐式原型指向构造函数
    obj.__proto__ = Constructor.prototype;
    var ret = Constructor.apply(obj, arguments);
    // 构造函数是否有return判断
    return typeof ret === 'object' ? ret : obj;
};

call的模拟实现

Function.prototype.call2 = function (context) {
    var context = context || window;
    context.fn = this; // this为调用call2的函数
    var args = [];
    for(var i = 1, len = arguments.length; i < len; i++) {
        args.push('arguments[' + i + ']');
    }
    var result = eval('context.fn(' + args +')');
    delete context.fn
    return result;
}

apply的模拟实现

Function.prototype.apply = function (context, arr) {
    var context = Object(context) || window;
    context.fn = this;
    var result;
    if (!arr) {
        result = context.fn();
    } else {
        var args = [];
        for (var i = 0, len = arr.length; i < len; i++) {
            args.push('arr[' + i + ']');
        }
        result = eval('context.fn(' + args + ')')
    }
    delete context.fn
    return result;
}

bind模拟实现

Function.prototype.bind2 = function (context) {
    if (typeof this !== "function") {
      throw new Error("Function.prototype.bind - what is trying to be bound is not callable");
    }
    var self = this;
    var args = Array.prototype.slice.call(arguments, 1);

    var fNOP = function () {};

    var fBound = function () {
        var bindArgs = Array.prototype.slice.call(arguments);
        // 判断是否为new调用
        return self.apply(this instanceof fNOP ? this : context, args.concat(bindArgs));
    }
    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
    return fBound;
}

防抖(debounce)

github.com/mqyqingfeng…

注: 第二版(基础)、第五版(拓展)

节流(throttle)

github.com/mqyqingfeng…

注: 第二版

参考

JavaScript深入之new的模拟实现

JavaScript深入之call和apply的模拟实现

JavaScript深入之bind的模拟实现