简体   繁体   English

this.someFunction.bind(this)是否多余?

[英]Is this.someFunction.bind(this) redundant?

I'm reading someone's code and I see the following: 我正在阅读某人的代码,并且看到以下内容:

this.device_name.changes().onValue(this.changeName.bind(this))

From what I understand, onValue takes a callback function, and that function is this.changeName.bind(this)) . 据我了解, onValue一个回调函数,而该函数是this.changeName.bind(this)) Correct me if I'm wrong: 如果我错了纠正我:

  • The default value of this in a function call refers the object with which the function was called upon. 函数调用中的this的默认值引用调用该函数的对象。
  • The .bind(someObject) method causes the function's this to refer to someObject instead, when the function gets executed. .bind(someObject)方法使函数的this在执行函数时改为引用someObject

Knowing this (heh), this.changeName.bind(this) seems redundant: the default value for this when calling this.changeName will be the same this that is passed in the bind parameter. 知道了这一点(嘿嘿), this.changeName.bind(this)似乎是多余的:为默认值this打电话时this.changeName将是相同的this是在通过bind参数。

So! 所以! Can the function be safely refactored to simply this.changeName with no differences in behavior? 可以安全地将函数重构为简单的this.changeName ,而在行为上没有差异吗?

No, the bind is very important here. 不,绑定在这里非常重要。

A function's this pointer is set at the time the function is called. 函数的this指针是在调用函数时设置的。 The call, in this case, is down inside whatever object is invoking the callback. 在这种情况下,该调用位于调用回调的任何对象内部。 Many objects just call with a this pointer either as null or (in the case of DOM objects) pointing to the DOM object itself. 许多对象只是使用this指针作为null或(对于DOM对象而言)指向DOM对象本身进行调用。

Using the bind function this way returns a new function that hard-wired the this reference to the value passed to bind. 以这种方式使用bind函数将返回一个新函数,该函数将this引用与传递给bind的值硬连接。 If you take out the bind, it'll completely hose up the this pointer. 如果取出绑定,它将完全弄清this指针。 It will DEFINITELY change the behavior. 它将彻底改变行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM