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.
source share