call,apply,bind 봉인

1621 단어
 var obj = {
        name: "zwb",
        say: function (a, b) {
            console.log(this.name, a, b)
        }
    }
    // //  obj.say()

    var sky = {
        name: 'xiaoli'
    }
    //  obj.say.call(sky)    

      //mycall 
    Function.prototype.mycall = function (newobj, ...argu) {
        var newobj = newobj || window
        // say 
        var fnName = Symbol(this.name)
        // say     
        newobj[fnName] = this
        // console.log(newobj)
        // 
        var val = newobj[fnName](...argu)
        delete newobj[fnName]
        //  console.log(val)
        return val
    }
    obj.say.mycall(sky, 'nihao', 'ma')


    //apply bind
    obj = {
        name: 'zs',
        say: function () {
            console.log(this.name, ...arguments)
        }
    }
    sky = {
        name: ' '
    }



    // apply
    Function.prototype.myapply = function (newName, argu) {
        var newName = newName || window
        var fnName = this.name
        // console.log(fnName)
        newName[fnName] = this
        return newName[fnName](...argu)
        delete newName[fnName]
    }
    obj.say.myapply(sky, [1, 2, 3])

    // bind
    Function.prototype.mybind = function (newName, ...argu) {
        var newName = newName || window
        that = this          // this , this 
        return function () {
            var all_new = argu.concat(...arguments)     //...arguments  
            that.myapply(newName, all_new)
        }
    }
    var newb = obj.say.mybind(sky, 1, 2, 3)
    newb(' ', ' ')

좋은 웹페이지 즐겨찾기