Creating arrays and objects


#1

how to create objects using constructor?


#2

First we write a function which by convention will have a Capital letter to start:

function Person(){

}

This function is to be the object model for all Person instances. What properties would be expected for such objects? name, age, job, and so on. We continue building the function by adding these as formal parameters...

function Person(name, age, job){

}

and now we write assignment statements that populate the internal instance object, this,

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

Another name for this is a custom object constructor as opposed to built in object constructors that come with JavaScript. With this we can now invoke instances of the custom object using the new operator:

var bill = new Person("Bill", 19, "student");
var mary = new Person("Mary", 25, "programmer");

In each instance, this is handed over to their respective object reference, bill and mary.

console.log(bill); // { name: 'Bill', age: 19, job: 'student' }
console.log(mary); // { name: 'Mary', age: 25, job: 'programmer' }

#3

If the above response is more than expected, let's take a step back and review objects.

var newObject = new Object();

The above creates a new object instance using the built-in Object() constructor. All objects in JavaScript are descended from this constructor.

Another, less formal but just as valid way to create an object instance is to use literal notation:

var literalObject = {};

Closer examination reveals that this object also uses the Object() constructor:

console.log(literalObject.constructor); // [Function: Object]

Using the literal notation, we can write a single object,

var john = {
    name: 'John',
    age: 20,
    job: 'proctor'
};

This is quite unlike the custom constructor we discussed above, and less common in refined code. It is handy for one-off objects, though. We should be well versed in this form of construction, as it is fundamental to the whole object concept.