模拟实现call和apply

234 阅读1分钟

call模拟实现

Function.prototype.call = function (context) {
    const context = context || window
    context.fn = this
    let args = []
    for (var i = 1; i < arguments.length; i++) {
        args.push('arguments[' + i + ']')
    }
    let result = eval('context.fn(' + args + ')')
    delete context.fn
    return result
}

apply模拟实现

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

bind模拟实现

Function.prototype.bind = function (context) {
    const self = this
    const args = Array.prototype.slice.call(arguments, 1)
    const fNOP = function () {}
    const fbound = function () {
        const bindArray = Array.prototype.slice.call(arguments)
        self.apply(this instanceof self ? this : context, args.contact(bindArray))
    }
    fNOP.prototype = this.prototype
    fbound.prototype = new fNOP()
    return fbound
}

new模拟实现

function New () {
    const obj = new Object()
    const Constructor = Array.prototype.slice(arguments, 1)
    obj.__proto__ = Constructor.prototype
    Constructor.apply(obj, arguments)
    return obj
}