Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule idea: no-unbound-this #120

Closed
captbaritone opened this issue Nov 6, 2016 · 2 comments
Closed

Rule idea: no-unbound-this #120

captbaritone opened this issue Nov 6, 2016 · 2 comments

Comments

@captbaritone
Copy link
Contributor

I'm working on this for my Underscore fork, and thought it might be a good fit here as well.

In our code base at work, I found a few places where folks were using the this keyword in an unbound callback. In such a case (assuming we are in the browser) this becomes window, which is probably not what you wanted. If you had wanted window, you should have written that.

This can be especially confusing in a Backbone app where views have a $ property which is a jQuery matcher scoped to the view. I found a few instances of us doing something like:

render: function() {
    _.each(models, function(model) {
        this.$('.foo').append(new SubView({mode: model}).render().el);
    });
}

This code appears to be appending to the "foo" element within this view, but it's actually appending to any "foo" element on the page since window.$ is the global jQuery object.

This plugin is in a unique place to catch these sorts of errors, since we know exactly how the anonymous functions are going to be used, and we know that they are not going to be bound at some later time.

This rule would, of course, have to apply only to callbacks for which lodash does not apply a binding. For example, invokeMap will automatically bind to the given object(s) so this should be allowed in the callback even if it's not bound by the user.

@ganimomer
Copy link
Contributor

Sounds like a good idea!
I'll implement it unless anyone beats me to it.
Also, it should make sure not to warn on arrow functions, since they don't have their own context.

@captbaritone
Copy link
Contributor Author

Yeah, arrow functions are a good edge case to make sure gets covered. Two others come to mind:

Explicitly bound functions:

_.map(list, function(a) { return a + this.n; }.bind(this));

Unbound this used in a child contex:

_.map(list, function(a) {
    var plusN = function(x) {
        return x + this.n;
    }
    plusN = plusN.bind(self);
    return plusN(a);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants