object - Javascript: Understanding Prototype chain -
i created simple class follows:
var class = function() {}; class.prototype.testobj = {a:2, b:3};
now if console.log(class.testobj)
undefined
. if create instance of class follows:
var instance = new class(); console.log(instance.testobj)
i expected output.
in understanding, variables treated objects , have prototype property. when key not found in object, prototype chain traversed key-value pair. in case of class, not traversing prototype chain.
what missing? additional new
keyword such property accessible?
you must clear
class()
constructor
, notinstance object
.class.testobject
returnundefined
becauseclass
doesn't haveproperty
.you can think of
prototype
recipe object. every function hasprototype
property used during creation of new instances , thatprototype
shared among of object instancesa constructor function used
new
create objectwhen
var instance = new class();
means creating instance object ofclass
, henceinstance
inheritprototype
properties ofclass
.test:
console.log(instance instanceof class); // => true console.log(instance.constructor === class); // => true console.log(object.prototype.isprototypeof(class)); // => true console.log(class.prototype.isprototypeof(instance)); // => true
Comments
Post a Comment