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?

  1. you must clear class() constructor, not instance object. class.testobject return undefined because class doesn't have property.

  2. you can think of prototype recipe object. every function has prototype property used during creation of new instances , that prototype shared among of object instances

  3. a constructor function used new create object

  4. when var instance = new class(); means creating instance object of class, hence instance inherit prototype properties of class.

  5. 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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -