美文网首页
手写bind函数

手写bind函数

作者: 小猪佩奇的王子 | 来源:发表于2019-11-04 08:54 被阅读0次

bind用于改变this指向

Function.prototype.myBind = function(obj, ...args) {
   var self = this
   var fn = function() {
       var _this = this instanceof self ? this : obj
       return self.apply(_this, args.concat([...arguments]))
   }
   fn.prototype = this.prototype
   return fn
}

测试一下

function foo(name) {
    this.name = name
}

var obj = {}

//上下文 功能  done
var bar = foo.myBind(obj)
bar("jack")
console.log(obj.name) //'jack'

// 参数 功能   done
var tar = foo.myBind(obj, "rose")
tar()
console.log(obj.name) //'rose'
// new 功能   error
var alice = new bar("alice")
console.log(obj.name) //alice   obj name should be 'jack'
console.log(alice.name)

相关文章

网友评论

      本文标题:手写bind函数

      本文链接:https://www.haomeiwen.com/subject/gzjrbctx.html