Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How does JavaScript .prototype work?

I'm not that into dynamic programming languages but rather I've composed something reasonable of JavaScript code. I never truly got my head around this prototype-based programming, does anybody know how this works?

var obj = new Object();
obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();


I recollect a lot of conversation I had with individuals some time back (I'm not by and large sure the thing I'm doing) but rather as I get it, there's no understanding of a class. It's simply an object, and instances of those objects are clones of the first, correct?

In any case, what is the specific goal behind this ".prototype" property in JavaScript? How can it identify with starting up objects?

Update: correct way
var obj = new Object(); // not a functional object
obj.prototype.test = function() { alert('Hello?'); }; // this is wrong!

function MyObject() {} // a first class functional object
MyObject.prototype.test = function() { alert('OK'); } // OK
by

2 Answers

aashaykumar
prototype allows you to make classes. if you do not use prototype then it becomes a static.

Here is a short example.

var obj = new Object();
obj.test = function() { alert('Hello?'); };

In the above case, you have static funcation call test. This function can be accessed only by obj.test where you can imagine obj to be a class.

where as in the below code

function obj()
{
}

obj.prototype.test = function() { alert('Hello?'); };
var obj2 = new obj();
obj2.test();

The obj has become a class which can now be instantiated. Multiple instances of obj can exist and they all have the test function.

The above is my understanding. I am making it a community wiki, so people can correct me if I am wrong.
sandhya6gczb
The interface to standard classes becomes extensible. For example, you are using the Array class and you also need to add a custom serializer for all your array objects. Would you spend time coding up a subclass, or use composition or ... The prototype property solves this by letting the users control the exact set of members/methods available to a class.

Think of prototypes as an extra vtable-pointer. When some members are missing from the original class, the prototype is looked up at runtime.

Login / Signup to Answer the Question.