The difference between JavaScript reference type objects and regular objects

I am currently participating in a JavaScript learning process. I got confused with objects (link type and simple objects). Here are some codes that create an object (reference type):

function TheObject(first, last) { this.first = first; this.last = last; } TheObject.prototype.theMethod = function() { document.write("first : " + this.first + ", last : " + this.last + "</br>"); }; var anObject = new TheObject("Google", "Good"); anObject.theMethod(); 

Here are some other codes that also create the object (is it also a reference type?):

 var TheAnotherObject = function(first, last){ return { first : first, last : last, theMethod : function() { document.write("first : " + this.first + ", last : " + this.last + "</br>"); } }; } var anotherObject = TheAnotherObject("Yahoo", "Good"); anotherObject.theMethod(); 

Now my confusion is where the difference is between the two ways of creating objects. I know that I can create an object type in both directions (with the keyword "new"). Then what is the difference?

Please help me understand what I'm missing here. I know this is very important to understand, since JavaScript makes heavy use of functions and objects. Any help would be very much appreciated. Thanks in advance.

+4
source share
2 answers

The main difference:

The 1st approach defines theMethod method using prototype . This means that all instances created from this Class will use the same definition of this method ( theMethod )

Otherwise, the second approach defines a new theMethod method each time a new instance is created from Class . Obviously, with too many instances, this will be expensive, because several definitions will be made for theMethod .

+1
source

When it comes to creation, they are the same.

However, the difference is that the first way that a method is assigned to a prototype, which means only one instance of this method.

While in the second example, the method is defined for each new object.

So basically the method references do not match, which means o1.theMethod! = O2.theMethod

+1
source

All Articles