手寫Function.prototype.bind()函數

源碼:

支持new 綁定

//兼容IE6寫法
var slice = Array.prototype.slice
function ieBind(ieThis) {
    var args = slice.call(arguments, 1)
    // this就是調用bind的函數
    var fn = this
    function fn2 () {
        var args2 = slice.call(arguments, 0)
        return fn.apply(fn2.prototype.isPrototypeOf(this) ? this : ieThis, args.concat(args2))
    }
    fn2.prototype = fn.prototype
    return fn2
}

//es6寫法
function _bind(obj, ...arg) {
    const fn = this;// this就是調用bind的函數
    function fn2 (...arg2) {
        return fn.call(this instanceof fn2 ? this : obj, ...arg, ...arg2)
    }
    fn2.prototype = fn.prototype
    return fn2
}

// module.exports = ieBind;
module.exports = _bind;

if (!Function.prototype.bind) {//polyfill
    Function.prototype.bind = _bind
}

測試代碼:

const bind = require('../src/index')

test1('測試bind2是否能用')
test2('測試是否能綁定this成功')
test3('測試this, a, b 綁定成功')
test4('測試this, a綁定成功後,傳入b調用成功')
test5('new 的時候也綁定了a, b')
test6('new 的時候也綁定了a, b,並且函數中有 prototype.gogo')


function test1(message) {
    console.log(message)
    Function.prototype.bind2 = bind
    console.assert(Function.prototype.bind2 !== undefined)
}

function test2(message) {
    console.log(message)
    Function.prototype.bind2 = bind
    const f1 = function () {
        return this
    }
    const newF1 = f1.bind2({name: 'he'},1,2)
    console.assert(newF1().name === 'he')
}

function test3(message) {
    console.log(message)
    Function.prototype.bind2 = bind
    const f1 = function (a, b) {
        return [this, a, b]
    }
    const newF1 = f1.bind2({name: 'he'},111,2222)
    console.assert(newF1()[0].name === 'he','this')
    console.assert(newF1()[1] === 111,'a')
    console.assert(newF1()[2] === 2222,'b')
}

function test4(message) {
    console.log(message)
    Function.prototype.bind2 = bind
    const f1 = function (a, b) {
        return [this, a, b]
    }
    const newF1 = f1.bind2({name: 'he'},111)
    console.assert(newF1(2222)[0].name === 'he','this')
    console.assert(newF1(2222)[1] === 111,'a')
    console.assert(newF1(2222)[2] === 2222,'b')
}

function test5(message) {
    console.log(message)
    Function.prototype.bind2 = bind
    const f1 = function (a, b) {
        this.a = a
        this.b = b
    }
    const f2 = f1.bind2(undefined, 111, 222)
    const f3 = new f2()
    console.assert(f3.a === 111,'a')
    console.assert(f3.b === 222,'b')
}

function test6(message) {
    console.log(message)
    Function.prototype.bind2 = bind
    const f1 = function (a, b) {
        this.a = a
        this.b = b
    }
    f1.prototype.gogo = function () {}
    const f2 = f1.bind2(undefined, 111, 222)
    const f3 = new f2()
    console.assert(f3.a === 111,'a')
    console.assert(f3.b === 222,'b')
    console.assert(f1.prototype.isPrototypeOf(f3) ,'new後,原型是否繼承')
    console.assert(typeof f3.gogo === 'function')
}

 

發佈了69 篇原創文章 · 獲贊 32 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章