a guest Jan 18th, 2018 44 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. There are three main ways to deal with this in callbacks:
  2. 1. Create a lexically-scoped variable, as you are currently doing
  4. The two most common names for this new variable are that and self. I personally prefer using that because browsers have a global window property called self and my linter complains if I shadow it.
  6. function edit(req, res) {
  7.     var that = this,
  8.     db.User.findById('ABCD', function(err, user){
  10.     });
  11. };
  13. One advantage of this approach is that once the code is converted to using that you can add as many inner callbacks as you want and they will all seamlessly work due to lexical scoping. Another advantage is that its very simple and will work even on ancient browsers.
  14. 2. Use the .bind() method.
  16. Javascript functions have a .bind() method that lets you create a version of them that has a fixed this.
  18. function edit(req, res) {
  19.     db.User.findById('ABCD', (function(err, user){
  21.     }).bind(this));
  22. };
  24. When it comes to handling this, the bind method is specially useful for one-of callbacks where having to add a wrapper function would be more verbose:
  26. setTimeout(this.someMethod.bind(this), 500);
  28. var that = this;
  29. setTimeout(function(){ that.doSomething() }, 500);
  31. The main disadvantage of bind is that if you have nested callbacks then you also need to call bind on them. Additionally, IE <= 8 and some other old browsers, don't natively implement the bind method so you might need to use some sort of shimming library if you still have to support them.
  32. 3. If you need more fine-grained control of function scope or arguments, fall back to .call() and .apply()
  34. The more primitive ways to control function parameters in Javascript, including the this, are the .call() and .apply() methods. They let you call a function with whatever object as their this and whatever values as its parameters. apply is specially useful for implementing variadic functions, since it receives the argument list as an array.
  36. For example, here is a version of bind that receives the method to bind as a string. This lets us write down the this only once instead of twice.
  38. function myBind(obj, funcname){
  39.      return function(/**/){
  40.          return obj[funcname].apply(obj, arguments);
  41.      };
  42. }
  44. setTimeout(myBind(this, 'someMethod'), 500);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand