Creating a new object....this whole section just seems to be wrong and full of info that conflicts with other sources I've read...?


#1

Sooo....creating an object. Codecademy says literal notation uses curly brackets {}, and that the creator function uses syntax like this:

var myObj();
myObj.name : "Lizzie",
myObj.age : 27,

etc.

But this just seems to be like another way of writing literal notation. As far as I can tell, literal notation is like creating one object, one time, whereas the object creator function is...well, a function, that creates a blueprint that you can then use to assign a set of properties to multiple objects. What is the difference here?

Specifically, what does the code below mean:

function Person (name, age){
this.name = name
this.age=age
}

var lizzie = new Person("Lizzie",27);

console.log(lizzie.age);

The above makes total sense to me - that an object creator is like a mechanism that can print out object properties based on values that have been fed to it. I do not understand the Codecademy "creator" they are teaching in this section.

Help?


#2

That would be,

var myObj = new Object();
myObj.name = "Lizzie";
myObj.age = 27;

This is known as the 'constructor' method for creating new objects. In truth, the literal syntax still invokes this constructor behind the scenes.

var myObj = {};

This object will still inherit from Object.prototype.

Dot notation is property specific and has no dynamic aspect to it. The property names are either already defined, so accessed, or not defined, so created.

var myObj = {
    name: "Lizzie",
    age: 27
};

This is a single statement, as compared to the constructor method's three statements. It is a nice little package.

The above is a custom constructor which is a template for new object instances of the Person class. We can write this function once, and call upon it anytime we wish to add a new person to the mix.

More will be covered shortly, so I don't wish to get too far ahead of the curve. Keep forging on...