Objects in JS

Objects in JS can be created by:

  1. Use of variables
  2. Use of functions
// table variable                      |              // use of function
var table = {                          |              var table = function() {
    "legs":4,                          |                  this.legs = 4;
    "color":"brown",                   |                  this.color = "brown";
    "material":"wood"                  |                  this.material = "wood";
};                                     |              };

An instance of these objects can be created as:

var myTable = new table();

Arguments can be passed as needed in the constructor with corresponding changes in definition of the constructor. All the variables defined as property of this are public. In order to make a variable private, var keyword is used. Private variables are created to control changes that happen to their values from outside. Functions to modify these values are then defined within the constructor. This is illustrated in Bike object below.

var car = function() {
    var speed = 20;            // private variable

    // public methods below
    this.accelerate = function(paceup) {
        speed += change;
    };

    this.decelerate = function() {
        speed -= 5;
    };

    this.getSpeed = function() {
        return speed;
    };
};

Leave a Reply

Follow

Get notified with the latest posts

Plugin Supporter WordPress Post Navigation
%d bloggers like this: