How does JavaScript .prototype work? -




i'm not dynamic programming languages, i've written fair share of javascript code. never got head around prototype-based programming, 1 know how works?

var obj = new object(); // not functional object obj.prototype.test = function() { alert('hello?'); }; // wrong!  function myobject() {} // first class functional object myobject.prototype.test = function() { alert('ok'); } // ok 

i remember lot discussion had people while (i'm not sure i'm doing) understand it, there's no concept of class. it's object, , instances of objects clones of original, right?

but exact purpose of .prototype property in javascript? how relate instantiating objects?


edit

these slides helped lot understand topic.

every javascript object has internal property called [[prototype]]. if property via obj.propname or obj['propname'] , object not have such property - can checked via obj.hasownproperty('propname') - runtime looks property in object referenced [[prototype]] instead. if prototype-object doesn't have such property, prototype checked in turn, walking original object's prototype-chain until match found or end reached.

some javascript implementations allow direct access [[prototype]] property, eg via non-standard property named __proto__. in general, it's possible set object's prototype during object creation: if create new object via new func(), object's [[prototype]] property set object referenced func.prototype.

this allows simulate classes in javascript, although javascript's inheritance system - have seen - prototypical, , not class-based:

just think of constructor functions classes , properties of prototype (ie of object referenced constructor function's prototype property) shared members, ie members same each instance. in class-based systems, methods implemented same way each instance, methods added prototype, whereas object's fields instance-specific , therefore added object during construction.





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -