Reputation: 2969
Which should be the better approach to write JavaScript code, and why?
1)
var myClass = function(){}
myClass.prototype.init = function(x, y){
this.width = x;
this.height = y;
}
myClass.prototype.show = function(){
alert("width = "+ this.width+" height = "+ this.height);
}
2)
var myObj = {
init : function(x, y)
{
this.width = x;
this.height = y;
},
show : function()
{
alert("width = "+ this.width+" height = "+ this.height);
}
}
Upvotes: 2
Views: 63
Reputation: 630637
What you have are 2 totally different things, the first is a way to create a "class" of object, you can have many instances, the second is a single object...so they serve very different purposes.
Do you need many objects, all with their own properties? then the first is a must (there are many forms of this when it comes to inheritance, etc...but the basic function
structure is what I mean).
Do you need just one object with some variables/methods? then go with the second.
Upvotes: 4