Javascript object constructor never called using literal?

There seem to be many different answers to the differences and similarities between constructor and literal for creating objects in Javascript. I recently read that "when defining an object through object literary notation, the Object constructor is never called." (This statement is also true when creating arrays.) I know the "new" keywords are what sets the initialized Object keyword "this" when using constructor notation. Likewise, the "this" keyword is not specified when creating objects with literal notation, and is that what the above sentence means "the object's constructor is never called"?

+3


source to share


1 answer


The value this

will be available inside the object immediately after the object literal is created (however, it always depends on the context ), This is better explained 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

      


Regarding the suggestion you provided:

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

This is not accurate. Behind the scenes, the constructor is called Object

(or at least it behaves as if it were). I believe this suggestion refers to the difference between this:

var obj = { foo : true };

      



and this:

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

      

Both versions will create very similar (but not identical) objects. Some of the differences are:

  • In the constructor version, you can run additional code (like a function call) at the same time as the object is created (just call some function from the constructor).

  • In a literal version obj instanceof Object === true

    . In the constructor version, obj instanceof Object

    and obj instanceof Foo

    are true

    .

There are other differences as well, but these two are perhaps the most noticeable. Also, I would like to clarify what you seem to be misunderstanding:

I know the "new" keywords are what sets the initialized Object keyword "this" when using constructor notation.

This is not true. Although you can refer to this

within a constructor, the value this

is determined dynamically (for example, when a method is called). I suggest you read the MDN documentation page onthis

to get a better understanding.

+3


source







All Articles