Maintaining the reference to “this” in Javascript when using callbacks and closures

后端 未结 3 481
春和景丽
春和景丽 2020-11-30 20:16

I find myself assigning \"this\" to a variable so I can easily use it in callbacks and closures.

Is this bad practice? Is there a better way of referring back to the

3条回答
  •  粉色の甜心
    2020-11-30 21:01

    Unfortunately this is the well-established way to do this, although that is a widespread naming convention for this "copy".

    You can also try:

    db.User.findById('ABCD', this.foo.bind(this));
    

    But this approach requires foo() to have exactly the same signature as the one expected by findById() (in your example you are skipping err).

提交回复
热议问题