Adding Properties and Methods

There are two different options when we want to create new properties/methods.

The first option is to create them only for one of the created objects.

Example:

function myObject (n,a,j) { 
this.name= n; 
this.age = a; 
this.job=j; 
this.nameAge = function(){
                return this.name + " " + this.age;
    }
}

var student1 = new myObject("Aris","24");

var student2 = new myObject("Peter","24");

student1.hobby = "cinema";

student1.addMethod = function () { return this.job + " " + this.hobby; };

In this case, only "student1" object has the new property and method.

The property should have an assigned value whereas method follows the same syntax with the one used inside the constructor.

What do you think will happen if we try to access the "hobby" property in "student2" object? Open your console and type the appropriate code to see the result.

View source:

Console will give us the message: "undefined". Only "student1" has this property.

The second option is to add properties or methods, directly inside the constructor function.

In this case, we use the same syntax discussed in the previous chapter. Properties and Methods added inside the constructor are applied to all created objects.