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.testobjectreturnundefinedbecauseclassdoesn't haveproperty.you can think of
prototyperecipe object. every function hasprototypeproperty used during creation of new instances , thatprototypeshared among of object instancesa constructor function used
newcreate objectwhen
var instance = new class();means creating instance object ofclass, henceinstanceinheritprototypeproperties 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