4

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?
 });
});
Wilman
591 gold badge1 silver badge12 bronze badges
asked Aug 10, 2015 at 11:28

1 Answer 1

3

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.

answered Aug 11, 2015 at 6:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.