Which method of creating javascript objects is better?
Posted
by Germaine
on Stack Overflow
See other posts from Stack Overflow
or by Germaine
Published on 2010-05-04T02:30:34Z
Indexed on
2010/05/04
2:38 UTC
Read the original article
Hit count: 384
JavaScript
I've seen objects defined in two different ways, which function similarly, but are, of course, fundamentally different. You can do it either like this:
var myobject = {property: 'hello',
act: function() {
this.property += ' world';
}};
and like this:
function myobject() {
this.property = 'hello';
this.act = function() {
this.property += 'world';
}
}
The second method could create objects like so
var newobj = new myobject();
but you could do something similar using the first notation by making the object the return value of a function. The new keyword has the advantage of being able to pass parameters that can be used to initialize the properties of the object, but you could just as easily add an init function to the first kind of object.
Just wondering if besides these two differences, if there was a fundamental difference that made one method definitely better than the other method.
© Stack Overflow or respective owner