Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JSLint forbid the "this" keyword?

Consider this simple example:

"use strict";
var Foo = {
    field: 0,
    func: function () {
        this.field = 4;
    }
}

JSLint throws the error:

Unexpected 'this'. At the line "this.field = 4".

I've seem some questions here in StackOverflow asking for this, and in all the cases, the answer was just to enable the "Tolerate this" flag. However, I'm interested in why do the JSLint creators think the use of "this" is (or might lead to) an error.

Also, how would I implement member functions without the "this" keyword and without expecting the user to pass the instance as the first argument?

EDIT Maybe I didn't make myself clear enough in that this question, despite looking similar doesn't have an answer to what I'm asking: JSLint Error: Unexpected 'this'

The problem with that question is not the question itself but rather the answers it got. Note how the accepted answer is: "My suggestion is: tell JSLint to shut up". And I specifically say in my post that this is not a valid answer to me, as I want to understand why is the use of this forbidden by JSLint, not how to avoid that error.

like image 539
Setzer22 Avatar asked Oct 31 '22 21:10

Setzer22


1 Answers

As @pdenes pointed out in the comments, there has been some discussion on the topic here: https://plus.google.com/communities/104441363299760713736/s/Berriman%20new%20version%20fails

There's also a Douglas Crockford youtube talk called "The Better Parts" in which Douglas exposes some of his opinions on this, and proposes a (in his opinion) better way to make a constructor.

The proposed constructor pattern looks like this (directly taken from his talk, it also illustrates some features of ES6):

function constructor(specs) {
    let {member} = spec, 
        {other} = other_constructor(spec),
        method = function() {

        };
    return Object.freeze({
        method,
        other
    });
}

The "pattern", as I understand it, is to avoid using "this" and any other way of object creation (by means of new, or Object.create), getting also rid of prototypal inheritance.

At this point, the constructor is now a function that returns an object (in this case, frozen, but there's no need for that actually).

All the "object-oriented" stuff is achieved by storing the members and methods in the constructor's closure, and member function can refer to those by name because they're present in the current scope. That successfully avoids the use of "this".

Sadly, the real answer I get from this is that there are many convoluted ways to create an object in javascript, and IMO each one has its flaws. JSLint is a nice tool, but no one should be following it without doing some research and understanding why are those errors given. Especially when no real, comprehensive reason is offered. Not even by the author.

like image 188
Setzer22 Avatar answered Nov 12 '22 20:11

Setzer22