this. somefunction .bind(this)是否多余?
Is this.someFunction.bind(this) redundant?
我正在阅读某人的代码,我看到以下内容:
this.device_name.changes().onValue(this.changeName.bind(this))
据我所知,onValue
有一个回调函数,这个函数就是this.changeName.bind(this))
。如果我说错了请纠正:
- 函数调用中
this
的默认值是指调用该函数的对象。 -
.bind(someObject)
方法导致函数的this
在函数执行时指向someObject
。
知道这个(嘿),this.changeName.bind(this)
似乎是多余的:调用this.changeName
时this
的默认值将与在bind
参数中传递的this
相同。
如此!该函数可以安全地重构为简单的this.changeName
而没有行为上的差异吗?
不,绑定在这里非常重要。
函数的this
指针是在调用函数时设置的。在这种情况下,调用在调用回调的对象内部。许多对象只是使用this指针进行调用,要么为空,要么(在DOM对象的情况下)指向DOM对象本身。
以这种方式使用bind函数返回一个新函数,该函数将this
引用硬连接到传递给bind的值。如果取出绑定,它将完全占用this
指针。
相关文章:
- 使用php或javascript从facebook相册URL中删除多余的部分
- $(this).prop('property') vs. this.property
- Twitter Bootstrap typeahead:使用“this”获取上下文/调用元素
- 在另一个函数中使用变量this
- this.router在AngularJS 2中未定义
- reactjs this.refs vs document.getElementById
- JavaScript 中的嵌套函数和 “this” 关键字
- React+Meteor:this.ops返回未定义
- javascript中对象构造函数中的var属性与this.properties
- 函数中this和var之间的区别
- jQuery(this).Pparent().Pparente().Prent().find()在iPad上不起作用
- Understanding Javascript scope with "var that = this&qu
- 定义this.properties或objectName.properties的javascript JSON对象
- Object.prototype using 'this'
- 在JavaScript类型的函数中避免self-this
- 如何使用(this)访问Angular 2 http rxjs catch函数中的对象属性
- Javascript 对象和 this 关键字
- jQuery使用ajax自动完成问题-TypeError:this.source不是函数
- reactjs无法将this.pops传递到react图表列表中
- this. somefunction .bind(this)是否多余?