Prerequisite - understanding of proto
Simple Example
- The Object.create() method creates a new object, using an existing object as the prototype of the newly created object. Confusing? Let's understand it using an example
let src = {a: 1};
let result = Object.create(src);
console.log(result) // prints {}
console.log(result.__proto__ === src); // true
console.log(result.a); // prints 1
- So, by second log, We understand that if we make any changes in result.proto, it will change the src. Let's quickly check that
result.__proto__.a = 2;
console.log(src.a); // prints 2
- What if we want to attach directly some property to the created object? We can do so by passing a second argument as an object like below
let src = {a: 1};
let result2 = Object.create(src, {
b : {
value: 3
}
});
console.log(result2) // prints {b: 3}
result2.hasOwnProperty('b') // prints true
- Notice, I didn't use {b:3} directly in the argument but I had to pass a property descriptor object
How is it used in case of function and prototype
- Let's take an example real quick. So, In below example, A completely new object was created with proto pointing to Base.Prototype and is assigned to Child.prototype.
- It can be powerfully used to achieve inheritance in JS
function Base() {
this.a = 1;
}
Base.prototype.b = 2;
function Child() {}
Child.prototype = Object.create(Base.prototype);
console.log(Child.prototype.__proto__ === Base.prototype);
Child.prototype.__proto__.b = 3;
console.log(Base.prototype.b); // prints 3