Skip to content

Instantly share code, notes, and snippets.

@coto
Last active January 5, 2016 21:33
Show Gist options
  • Save coto/765973 to your computer and use it in GitHub Desktop.
Save coto/765973 to your computer and use it in GitHub Desktop.
Classes/Objects in JavaScript: Different ways to define them
/***********************************
Author: Rodrigo Augosto C.
Twitter: http://twitter.com/coto
Date: Dec 17, 2010
************************************/
// ###### Example 1: Object Using new Object() ######
person = new Object();
person.name = "Brendan Eich";
person.height = "6Ft";
person.records = [12, 23, 34];
person.run = function() {
this.state = "running";
this.speed = "4ms^-1";
document.write(this.name + " is "+this.state+" and his last record was " + this.records[2] + " seconds");
}
person.run();
// ###### Example 2: Object Using JSON ######
person = {
name : "John Resig",
height : "6Ft",
records : [12, 23, 34],
run : function(){
this.state = "running";
this.speed = "4ms^-1";
document.write(this.name + " is "+this.state+" and his last record is " + this.records[2] + " seconds");
}
};
person.run();
// ###### Example 3: Class using function and prototype ######
function Corredor(name, height) {
this.name = name;
this.height = height;
this.records = [2, 3, 3];
this.run = function() {
this.state = "running";
this.speed = "4ms^-1";
document.write("<p>" +this.name + " is "+this.state+" and his last record is " + this.records[2] + " seconds</p>");
}
}
person1 = new Corredor("Fulano");
person1.run();
person2 = new Corredor("Mengano");
person2.run();
// Prototype to add a method
Corredor.prototype.changeName = function(name) {
this.name = name;
}
cat1.changeName("Sultano");
cat1.run()
// ### It can help you to get information from these objects ###
// alert(typeof person);
// for(x in person) alert( x + " = " + person[ x ] )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment