0
点赞
收藏
分享

微信扫一扫

js的bind 的原理

js 的bind 方法主要绑定this的指向 bind 方法也会返回是个bind后的函数。 知道它功能我们就可以自定义bind功能 let object= {name:'jeff'} function fn(){ console.log(this.name) } //自定band方法 Function.prototype._bind = function(context){ let that = this // 指定this
return function(){ that.apply(context) } } let hand = fn._bind();//测试 上面的bind 没有考虑到带参数的函数 // 下面带参数的 Function.prototype._bind = function(context){ let that = this // 指定this
let bindArg
=Array.proptype.slice.call(argurments,1) //取出类参数中第一位 return function(){ let arg = Array.proptype.slice.call(argurments)
that.apply(context,arg.concat(bindArg)) } }

// 假如考虑如果被new的函数,当前的this就是当前的函数

Function.prototype._bind = function(context){ let that = this // 指定this
let bindArg
=Array.proptype.slice.call(argurments,1) //取出类参数中第一位 function tempFn (){} return function _fn(){ let arg = Array.proptype.slice.call(argurments)
that.apply( this instannceof _fn ? this : context,arg.concat(bindArg)) } tempFn.proptype = this.proptype // 关联函数 _fn.proptype = new temFn(); return _fn }

举报

相关推荐

0 条评论