Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two different ways to make javascript objects

Tags:

javascript

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

like image 559
soleiljy Avatar asked Oct 21 '22 03:10

soleiljy


1 Answers

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.

like image 105
Guffa Avatar answered Nov 04 '22 21:11

Guffa