soleiljy
soleiljy

Reputation: 1131

Two different ways to make javascript objects

I am new to Javascript and now studying it...

var person = function() {
    this.name = "name"
};

var person2 = function() {
    var obj = {};
    obj.name = "name";
    return obj;
};

Let's suppose we have two functions shown above. It seems that objects can be created by using either of the functions. For example)

var p = new person();
var p2 = new person2();

My question is: What's difference between person vs person2? Are they exactly the same? If not which one is a more preferable way to use?

Thanks

Upvotes: 5

Views: 126

Answers (2)

Alex Shesterov
Alex Shesterov

Reputation: 27525

The difference is in the way you use the functions.

The first one is intended to be used as a constructor, this being set to the newly created object. It is intended to be used in combination with the operator new, as follows:

var bill = new person(); 

This is just like a normal constructor as in typical OOP language.


The second one is intended to be used as a normal function (without new), e.g.:

var bill = person(); 

You can use this way of object creation in combination with the builder pattern.

Upvotes: 1

Guffa
Guffa

Reputation: 700322

The normal way of creating an object is the first way.

The second way will create two objects, and one will be discarded. One object will be created before the function is called, just as with the first method, but because the function returns another object the first object will be discarded and the returned object will be used instead.

An important difference between the methods is that the second one can't use a prototype. Anything that you put in the prototype of the function will be applied to the object that ends up being discarded.

Upvotes: 2

Related Questions