Methods inside Constructor Functions

Similar to JavaScript objects, Constructor functions can also have methods.

Example of a method inside constructor function:

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

Let's create two new objects:

Object 1

var student1 = new myObject("Helen");

Object 2

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

How would you call the method for Object 2?

Answer:

console.log(student2.nameAge());

What would be the result if we call the method on object 1? Open your console and type the appropiate code to see the result.

Answer:

The console will give you the message: "Helen undefined". This is because object 1 had only value for the parameter "n". Thus, "a" is undefined.

Exercise

  1. Open your editor, create a new file and save it as exersice12.3.03.html in the folder "yourNameWEB2JS".
  2. Modifying the above code, create 2 new objects. The browser's output should be as shown in the following image:

Solution: