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";
}
function Parent(){
this.someProperty = "Some Property";
}
//Extend Parent's prototype
Parent.prototype.someMethod = function(){
console.log("Some Method");
}
Parent.prototype.someMethod = function(){
console.log("Some Method");
}
//Define Child class, making sure Parent's ctor is called
function Child(){
Parent.call(this);
}
function Child(){
Parent.call(this);
}
//Extend Child's prototype
Child.prototype.someOtherProperty = "Some other property";
Child.prototype.someOtherProperty = "Some other property";
//Change the Child's prototype here to the Parent's prototype
Child.prototype = Object.create(Parent.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
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 consideredundefined
.
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