You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
varmodule={x: 42,getX: function(){returnthis.x;}}module.getX.prototype.sayHi=function(name){return'I am '+name}varunboundGetX=module.getXconsole.log(module.getX(),newmodule.getX().sayHi('module.getX'))// 42 "I am module.getX" console.log(unboundGetX(),newunboundGetX().sayHi('unboundGetX'))// undefined "I am unboundGetX"
varunboundGetX=module.getXvarboundGetx=module.getX.newbind(module)console.log(module.getX(),newmodule.getX().sayHi('module.getX'))// 42 "I am module.getX" console.log(unboundGetX(),newunboundGetX().sayHi('unboundGetX'))// undefined "I am unboundGetX"console.log(boundGetx(),newboundGetx().sayHi('boundGetx'))//42 "I am boundGetx"
boundGetx.prototype.sayHi=function(name){return'changed,I am '+name}console.log(newboundGetx().sayHi('boundGetx'))// changed,I am boundGetxconsole.log(newmodule.getX().sayHi('module.getX'))//changed,I am module.getX
Function.prototype.newbind=function(){constoThis=Array.prototype.shift.call(arguments)// 第1个参数constparams=Array.prototype.slice.call(arguments)oThis.fn=this//函数functionconstres=function(){returnoThis.fn.apply(oThis,params.concat(Array.prototype.slice.call(arguments)))//修改函数function的this指向并执行}if(this.prototype){res.prototype=newthis()//维护原型关系}returnres}varmodule={x: 42,getX: function(val){returnval ? val : this.x}}module.getX.prototype.sayHi=function(name){return'I am '+name}varunboundGetX=module.getX;//使用bind修改unboundGetX的this指向varboundGetx=module.getX.newbind(module)console.log(module.getX(),newmodule.getX().sayHi('module.getX'))//this指向变量moduleconsole.log(unboundGetX(),newunboundGetX().sayHi('unboundGetX'))//this指向window,所以为undefinedconsole.log(boundGetx(),newboundGetx().sayHi('boundGetx'))//this指向变量modulconsole.error('---------sayHi was changed------')boundGetx.prototype.sayHi=function(name){return'changed,I am '+name}console.log(newboundGetx().sayHi('boundGetx'))console.log(newmodule.getX().sayHi('module.getX'))
The text was updated successfully, but these errors were encountered:
bind()的作用
在js中,我们通常使用
bind()
来修改this指向unboundGetX()的this指向window,所以输出
this.x为undefined
,现在,我们使用bind来修改unboundGetX()的this指向可以看到bind()返回的函数,其this指向已经指向了module,
this.x为=42
bind()的实现原理
现在,我们来尝试实现一个newbind(),使得boundGetx的this指向变量module
newbind()实现
此时newbind已经返回了1个新的函数
验证newbind正确性
可以发现unboundGetX()仍然输出undefined,但是boundGetx()其this已经指向了module,
this.x为42
注意事项
res.prototype = this.prototype
存在问题,由于对象属于引用类型,这样的写法会导致module.getX.prototype会随着boundGetx.prototype
改变,我们尝试修改一下boundGetx.prototypebind与call,apply的差别
bind返回的是1个函数,call,apply返回值为undefined
完整代码
codesandbox 运行代码
The text was updated successfully, but these errors were encountered: