Every JavaScript programmer is familiar with this "problem" (it can be considered as a feature, depending on various conditions) - this is lately binded:

let foo = {
    bar(){return this;}
let _bar = foo.bar;
_bar() === foo.bar(); // false; 

_bar() evaluates to global object or undefined depending on presence of 'use strict' directive and foo.bar() evaluates to foo.

Node.js have a convention of providing "error first" callbacks.

My question is - what should be set by library as this of callback? EventEmitter instances set this to emitter instance and it would be most obvious solution for me - but I couldn't find popular libraries using this pattern.

Native Array instances methods use pattern Array.prototype.method = function(fn, thisArg=null){} with last argument being this context. It seems to be good solution for constant-length methods, but for variadic functions it have edge cases with this set to an instance of function.

Speaking outside of Node, jQuery use $.ajax({context: thisArg}) to set this argument of callback.

So what would be the best solution for eg. class abstracting away implementation details of user?

User.getUserByLogin('nick', function(err, user) {
     // user is User instance
     user.updateUser({name: 'new name'}, function(err){
         // what SHOULD be `this` here?

1 Answer 1


My general first recommendation about this, is don't use it, it makes programs harder to read with no real upside. The primary exception being constructor functions.

In a library you can just leave this of a callback being global/undefined, anything you would pass as a this value may as well be passed as another parameter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.