Getting to Learn JavaScript Objects - Part 2

Guest Posts Paolo Nikko Nuñal

In our last tutorial we talked about JavaScript objects, this is our second part of the series in which we will be dealing with objects adding methods, properties and more.

In the previous tutorial we can create object using constructor. This is how you can create it using JavaScript object instances.

You can do so as seen in the example below.

var manager  =  new person("Jake","Doe", 50);
var employee =  new person("John","Draper", 20);


Adding Properties to Objects

You can add additional properties to an existing object by giving it any value. Let us assume that we have the properties "salary" and "employeeType". You can do so by doing this.

manager.salary = 20000;
manager.employeeType = "REGULAR";
alert(manager.salary);


In which it will display the salary of 200000.

Methods can also be attached, pretty much the same as objects. Always remember that JavaScript doesn't have "classes" and if you are planning on creating a getters and setters or any type of method you have to do it inside the constructor function.

function person(fname,lname,age){
    this.fname = fname;
    this.lname = lname;
    this.age   = age;

    this.setFName = setFName;

    function setFName(fname){
       this.fname = fname;
    }
}


The method setFname(fname) sets the first name of the person.

function person(fname,lname,age){
    this.fname = fname;
    this.lname = lname;
    this.age   = age;

    this.setFName = setFName;

    function setFName(fname){
       this.fname = fname;
    }
}

var manager = new person("John","Reese",24);
manager.setFName("Michael");


So when you run the program, you will see to it that the manger's first name is changed from John to Michael.