Friday, March 16, 2012

Javascript objects and classes; private and public methods and properties

1) Object literals

var Object = {
   
    speed : 0,
   
    setSpeed : function(speed) {
        this.speed = speed;
    },
   
    getSpeed : function() {
        return this.speed;
    }
   
}

Example:
Object.setSpeed(150);
var speed = Object.getSpeed();

All properties and methods of the object literal are public.

2) Classes

function Class1() {
   
    // private property example
    var name = 'Random name here';
   
    // public property example
    this.speed = 0;


    // private method example
    function getName() {
        return name;
    }
   
    // public method example
    this.setSpeed = function(speed) {
        this.speed = speed;
    }
   
    // public method example
    this.getSpeed = function() {
        return this.speed;
    }
   
   
}

Example:
var Object1 = new Class1();
Object1.setSpeed(150);
var speed = Object1.getSpeed();

No comments: