gpt4 book ai didi

javascript - this.someFunction.bind(this) 是多余的吗?

转载 作者:行者123 更新时间:2023-11-30 16:43:16 26 4
gpt4 key购买 nike

我正在阅读某人的代码,我看到以下内容:

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

据我了解,onValue 接受一个回调函数,该函数是 this.changeName.bind(this))。如果我错了请纠正我:

  • 函数调用中 this 的默认值是指调用该函数的对象。
  • .bind(someObject) 方法导致函数的 this 在函数执行时引用 someObject

知道这个(呵呵),this.changeName.bind(this) 似乎是多余的:调用 this.changeNamethis 的默认值> 将与 bind 参数中传递的 this 相同。

所以!能否将函数安全地重构为简单的 this.changeName 而在行为上没有差异?

最佳答案

不,绑定(bind)在这里很重要。

函数的 this 指针在调用函数时设置。在这种情况下,调用在调用回调的任何对象内部。许多对象只是使用 this 指针调用,或者作为 null 或(在 DOM 对象的情况下)指向 DOM 对象本身。

以这种方式使用绑定(bind)函数会返回一个新函数,该函数将 this 引用硬连接到传递给绑定(bind)的值。如果您取消绑定(bind),它将完全控制 this 指针。它肯定会改变行为。

关于javascript - this.someFunction.bind(this) 是多余的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31616926/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com