Below code demonstrates the prototype chaining concept in JavaScript:
// create object first person
var person1 = {
name : "Diana",
age : 27,
};
console.log(person1.__proto__);
console.log(person1.toString());
//Adding the function greetings in the root prototype
// so that all lower objects are able to derive it
Object.prototype.greetings = function() {
console.log("Hello "+this.name+"!");
}
//greet first person
// Diana
person1.greetings();
// create second person
// this inherits attributes from first person
var person2 = Object.create(person1);
person2.name = "Saina";
console.log(person2.name);
// greet second person
person2.greetings();
Diagram:
Refer:
Practice at:
http://jsbin.com
// create object first person
var person1 = {
name : "Diana",
age : 27,
};
console.log(person1.__proto__);
console.log(person1.toString());
//Adding the function greetings in the root prototype
// so that all lower objects are able to derive it
Object.prototype.greetings = function() {
console.log("Hello "+this.name+"!");
}
//greet first person
// Diana
person1.greetings();
// create second person
// this inherits attributes from first person
var person2 = Object.create(person1);
person2.name = "Saina";
console.log(person2.name);
// greet second person
person2.greetings();
Diagram:
Refer:
- http://kenneth-kin-lum.blogspot.com/2012/10/javascripts-pseudo-classical.html
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
Practice at:
http://jsbin.com
No comments:
Post a Comment