The second one is easier to debug due to:
the Person instance
* has a constructor property
* is an instanceof Person
Person.prototyp e.isPrototypeOf ( p ) is true.
Method 1 is popular, though, you're right! Closures are popular, too.
I really feel this is overused, especially in YUI.
I feel that using an object literal can be less explicit because
everything is an object, whereas a Person is a more specific type of
object.
One possible reason that might make method 1 (object literal approach)
favorable would be for a simple value object that is used right away
(such as Person).
Finally, If you can't have more than one Person instance, but want to
have a constructor, you can perform a simple entryCheck to the
constructor to make sure it's your factory getInstance method. Some
people might think this is complicated, but I actually like this
approach.
On Jul 4, 1:18 pm, Lee <REM0VElbspamt. ..@cox.netwrote :
howa said:
Method 1:
var Person = {
name: "",
sayHello: function() {
...
}
}
Method 2:
function Person(name) {
this.name = name;
}
var p = new Person("john");
While both is okay, I see a trend more and more people is using method
1, any reason?
The two methods accomplish different things.
Method 1 creates one variable named Person which is an
instance of an anonymous Object initialized with literal
data. If you have all of the data required to instantiate
all the Objects you're going to need, this is simple.
Method 2 creates a constructor of Person Objects, which
is then used to instantiate a new Person and assign a
reference to it to a variable named p.
The same constructor could also be used to construct as
many more Person Objects as you like, dynamically.
--