Wednesday, January 5, 2011

Object Oriented Javascript

Object Constructor
function Cat(name) {
  this.name = name;
  this.talk = function() {
     alert( this.name + " say meeow!" )
  }
}

Creating Objects
  • using constructor of defined object
    myCat = new Cat("Kuting");
    
  • using new Object()
    person = new Object()
    person.name = "Bel"
    person.run = function() {
      this.state = "running"
      alert( this.name + " is running!" )
    }
  • using literal notation
    person = {
       name : "Bel",
       siblings : ["Ana", "Marie"],
       run : function(){this.state = "running"; alert( this.name + " is running!" )}
    };
Prototyping - attaching a method to an object
Cat.prototype.changeName = function(name) {
   this.name = name;
}

References:
http://www.javascriptkit.com/javatutors/oopjs.shtml

No comments:

Post a Comment