Sunday, October 25, 2015

JavaScript - Changing Prototype dynamically

JavaScript prototype inheritance

/* We can change the prototype of a class in the prototype chain dynamically. Not that this may be a good idea at all. */
//Define a Parent class
function Parent(){
    this.someProperty = "Some Property";
}
//Extend Parent's prototype
Parent.prototype.someMethod = function(){
    console.log("Some Method");
}
//Define Child class, making sure Parent's ctor is called
function Child(){
    Parent.call(this);
}
//Extend Child's prototype
Child.prototype.someOtherProperty = "Some other property";
//Change the Child's prototype here to the Parent's prototype
Child.prototype = Object.create(Parent.prototype);
var child = new Child();
child.someMethod(); // "Some Method"
console.log(child.someProperty); // "Some Property"

console.log(child.someOtherProperty); //undefined
-----------------------------------------------------------------------------------------

Property lookups through the JavaScript prototype chain work as follows:
  • If the object has a property with the given name, that value is returned. (The hasOwnProperty method can be used to check if an object has a particular named property.)
  • If the object does not have the named property, the object’s prototype is checked
  • Since the prototype is an object as well, if it does not contain the property either, its parent’s prototype is checked.
  • This process continues up the prototype chain until the property is found.
  • If Object.prototype is reached and it does not have the property either, the property is considered undefined.
Understanding how prototypal inheritance and property lookups work is important in general for developers but is also essential because of its (sometimes significant) JavaScript performance ramifications. Most JavaScript engines use a dictionary-like data structure to store object properties. 


Each property access therefore requires a dynamic look-up in that data structure to resolve the property. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and C#.

For further reading, http://www.toptal.com/javascript/javascript-prototypes-scopes-and-performance-what-you-need-to-know

No comments:

Post a Comment