jetru
jetru

Reputation: 1993

Why do people access fields in JS constructors, but not set them?

I've been reading lots of code that looks like this:

function Constructor(foo) {
    this.bar;
}

for defining constructor methods. Ofcourse, that field read does nothing. Why is it there? In a lot of cases, I do not see comments or tags for documentation generators either.

Upvotes: 1

Views: 67

Answers (3)

Gabriel
Gabriel

Reputation: 600

The TreeParser code referenced is doing absolutely nothing. My guess is that the intention is either 1) to document the object's properties, or 2) the original author is conflating this.foo and this.foo = undefined, thinking that this.foo is akin to var foo. It is not.

For reference the TreeParser is quite similar to the following:

function MyStuff(someArg) {
    /**
     * Very brief someArg documentation here.
     */
    this.someArg;

    // Do some other stuff...

    this.someArg = someArg; // <-- This line actually does something useful
}

In short, there is no good reason to be writing code like this. Good documentation is important, but this is not good documentation.

Upvotes: 3

StackSlave
StackSlave

Reputation: 10617

The argument foo and this.foo are not the same thing. When you see this.foo it refers to a new instance of Constructor's foo property, while the argument foo passes in a value to the new Constructor instance, like:

function Whatever(foo){
  this.foo = foo;
}
var wht = new Whatever('What are you talking about?');
console.log(wht.foo); wht.foo = 'Something Else.'; console.log(wht.foo);
var wh = new Whatever('This in a different instance of the same constructor.');
console.log(wh.foo);

Upvotes: 0

garryp
garryp

Reputation: 5776

That code is doing absolutely nothing.

Upvotes: 3

Related Questions