JavaScript :: Creating Objects

[ Creating a Simple Object ]

All members are publicly accessible. In this example 'Person.name' and 'Person.getName()' both return the same results.

  
  var Person = new Object();
  Person.name = "Adam";
  Person.age = "35";
  Person.getName = function(){ return this.name; };
  Person.getAge = function(){ return this.age; };
  Person.setAge = function(age){ this.age = age; };
  

[ The Object Literal ]

Note that in this form, like in the example above, all members are publicly accessible.

  
  var Person = {
    name: "Adam",
    age: "35",
    getName: function(){ return this.name; },
    getAge: function(){ return this.age; },
    setAge: function(age){ this.age = age; }; 
  }
  

[ The Module Pattern ]

The module pattern allows you to have public and private class members. Trying to access 'p1.setName()' will result in an error since it is not a public member.

  
  var Person = function( name, age ){
    // private members
    var name = name,
        age = age,
        setName = function(name){ this.name = name };
    
    return { 
      // public members
      getName: function(){ return name },
      getAge: function(){ return age },
      setAge: function(age){ this.age = age }
    }
  }
  

[ Prototype Method ]

(Add example of using prototype property to add methods to a class)