I am wondering about javascript prototype. I know that prototyping enables the user to add new properties and methods to a constructor or an object.
I have used the following several times:
function Example() {}
Example.prototype.add = function () {};
Example.prototype.sub = someVar;
This way I can use Example.add as a function and Example.sub as an element of object.
But happens when someone writes something like this
Example.prototype = function() {
//Code
};
Any help?
Let’s take a look at a simple example:
When defining a few methods for the person prototype we would do this:
Or
Both do the same thing. I prefer the first version because it’s easier to read and needs less characters to write ( making the footprint of my code smaller ).
The only reason I could think of for using
is to create a private scope available only to the prototype of the Person. But this requires a self executing function which returns an object.
theAnswerToEverything will be a variable usable only by the methods of the Persons prototype. More complex examples could be created by using the same principle.