KMcA
KMcA

Reputation: 1203

Javascript Object constructor never called using literal notation?

There seems to be a lot of different answers for the differences and similarities between constructor and literal notation for creating objects in Javascript. I recently read that "when defining an object via object literal notation, the Object constructor is never actually called." (This statement also holds true when creating arrays). I know that the "new" keywords is what sets the initialized Object's "this" keyword when using constructor notation. So is the "this" keyword not set when creating objects with literal notation, and is that what the sentence above means when is says "the object constructor is never actually called"?

Upvotes: 3

Views: 491

Answers (1)

bfavaretto
bfavaretto

Reputation: 71918

The this value will be available inside the object immediately after the object literal has been created (however it always depends on the context). It's better to explain with an example:

var obj = {
    foo : true,
    // bar : this.foo, // THIS WOULD FAIL, this IS NOT AVAILABLE YET!
    baz : function() { 
       return this; // THIS IS OK, this WILL BE AVAILABLE 
                    // WHEN THE FUNCTION IS *CALLED*
    }
};

obj === obj.baz(); // true

Concerning the sentence you quoted:

when defining an object via object literal notation, the Object constructor is never actually called

That's not accurate. Behind the scenes, the Object constructor is called (or at least it behaves as if it were). I believe what the sentence refers to is the difference between this:

var obj = { foo : true };

and this:

function Foo() {
    this.foo = true;
}
var obj = new Foo();

Both versions will produce very similar (but not identical) objects. Here are some of the differences:

  • The constructor version allows you to run additional code (like calling a function) at the same time the object is being created (just call some function from the constructor).

  • In the literal version, obj instanceof Object === true. In the constructor version, obj instanceof Object and obj instanceof Foo are both true.

There are other differences, but maybe these two are the most notable. Also, I'd like to clarify something you seem to be misunderstanding:

I know that the "new" keywords is what sets the initialized Object's "this" keyword when using constructor notation.

That's not true. Despite the fact that you can refer to this from inside a constructor, the value of this is determined dynamically (when you call a method, for example). I suggest you read the MDN documentation page on this to understand that better.

Upvotes: 3

Related Questions