Friday, June 15, 2018

JavaScript - Object - Prototype Chaining - Verifying

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

No comments:

Post a Comment