Below code demonstrates the verification of 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);
//verifying the object inheritance
console.log(person2.__proto__ == person1);
console.log(person2.__proto__.__proto__ == Object.prototype);
console.log(Object.getPrototypeOf(person2) == person1);
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);
//verifying the object inheritance
console.log(person2.__proto__ == person1);
console.log(person2.__proto__.__proto__ == Object.prototype);
console.log(Object.getPrototypeOf(person2) == person1);
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