Perferred way to create object

H

howa

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?
 
L

Lee

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.


--
 
D

dhtmlkitchen

The second one is easier to debug due to:

the Person instance
* has a constructor property
* is an instanceof Person

Person.prototype.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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top