原生JavaScript实现call apply bind

102 阅读1分钟
  1. call
function Person(a,b,c,d) {
    return {
        name: this.name,
        a: a,
        b: b,
        c: c,
        d: d
    }
}
var obj = {
    name: '派派'
}
Function.prototype.newCall = function(obj) {
    obj = obj || window
    obj.p = this
    var newArguments = []
    for (let i = 1; i < arguments.length; i++) {
        newArguments.push("arguments[" + i "]")
    }
    var result = eval('obj.p(' + newArguments + ')')
    delete obj.p
    return result
}
var aaa = Person.newCall(obj, '可爱', '年轻', '阳光', '善良')
console.log(aaa)
  1. apply
function Person (a,b,c,d) {
    return {
        name: this.name,
        a: a,
        b: b,
        c: c,
        d: d
    }
}
var obj = {
    name: "派派" 
}
Function.prototype.newApply(obj, arr) {
    obj = obj || window
    obj.p = this
    var result
    if (!arr) {
        result = obj.p()
    } else {
        var newArguments = []
        for (let i = 0; i < arr.length; i++) {
            newArguments.push("arguments[" + i + "]")
        }
        result = eval('obj.p(' + newArguments + ')')
    } 
    delete obj.p
    return result
}
var aaa = Person.newApply(obj, ['可爱', '年轻', '善良', '阳光'])
console.log(aa)
  1. bind
function Person(a,b,c,d) {
    return {
        name: this.name,
        a: a,
        b: b,
        c: c,
        d: d
    }
}
var obj = {
    name: '派派'
}
Function.prototype.newBind = function (obj) {
    if (this instanceof !== 'function') throw new TypeError('错误')
    var that = this
    var arr = Array.prototype.slice.apply(arguments, 1)
    var o = function () {}
    var newf = function () {
        var arr2 = Array.prototype.slice.apply(arguments)
        var arrSum = arr.concat(arr2)
        if (this instanceof newf) {
            that.apply(this, arrSum)
        }
        else {
            that.apply(obj, arrySum)
        }
    }
    o.prototype = that.prototype
    new.prototype = new o
    return newf
}
var aaa = Person.bind(obj,'可爱', '年轻')('帅气')

var aaa = Person.bind(obj,'可爱', '年轻')
var bbb = new aaa('帅气')