Possible Duplicate:
How to “properly” create a custom object in JavaScript?
Sorry if this has been answered before but I’m a bit overwhelmed by the amount of choices offered to be in regard to creating custom objects in Javascript. I’m not sure of their respective strengths or weaknesses or whether or not they differ at all.
Here are some of the different ways I have found to construct objects:
1: New Object
person = new Object()
person.name = "Tim Scarfe"
person.height = "6Ft"
person.run = function() {
this.state = "running"
this.speed = "4ms^-1"
}
2: Literal Notation
timObject = {
property1 : "Hello",
property2 : "MmmMMm",
property3 : ["mmm", 2, 3, 6, "kkk"],
method1 : function(){alert("Method had been called" + this.property1)}
};
3: Functions
function AdBox() {
this.width = 200;
this.height = 60;
this.text = 'default ad text';
this.prototype.move = function() {
// code for move method goes here
}
}
this.prototype.display = function() {
// code
}
I even saw some more ways but they seemed less common.. As you can see I’m not exactly sure what the standard is when someone just wants a simple object with fields and methods.
Thanks for reading.
The first and second options are functionally identical. Most developers choose to use the literal notation because it’s a little shorter.
The third option is generally only used when you’re looking to create reusable objects (i.e. inheritance). In this case, the function acts as a “constructor” – which is a function that returns a new object instance that can inherit methods and properties defined in the constructor’s prototype.