Skip to content

polyfill Function.prototype.bind #34

Description

@scarcoco

polyfill Function.prototype.bind 函数

注意:构造函数和原型链

/**
 * polyfill bind function
 */
const slice = Array.prototype.slice
const toString = Object.prototype.toString

Function.prototype.bind = Function.prototype.bind || function () {
    const fn = this
    if (typeof target !== 'function' || toString.call(target) !== '[object Function]') {
        throw new TypeError('type error')
    }
    const bindThisArg = arguments[0]
    const extraArgs = slice.call(arguments, 1)

    function newFun() {
        const args = extraArgs.concat(slice.call(arguments))
        if (this instanceof newFun) {
            const ret = fn.apply(this, args)
            if (Object(ret) === ret) {
                return ret
            }
            return this
        }
        return fn.apply(bindThisArg, args)
    }

    if (fn.prototype) {
        const F = function() {}
        F.prototype = fn.prototype
        newFun.prototype = new F()
        newFun.prototype.constructor = fn
    }

    return newFun
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions