33
loading...
This website collects cookies to deliver better user experience
let randomObj = {};
console.log(randomObj.__proto__ === Object.prototype); // true
let objA = new A();
console.log(objA.__proto__ === A.prototype); // true
console.log(objA.prototype); // undefined
function Parent() {
this.p = 50;
}
Parent.prototype.patchedP = 100;
function Child() {
Parent.call(this);
this.c = 200;
}
// Object.create sets (Child.prototype).__proto__ = Parent.prototype
Child.prototype = Object.create(Parent.prototype);
// Resetting the child constructor may/may not be needed
Child.prototype.constructor = Child;
Child.prototype.patchedC = 400;
console.log(new Child().p); // 50 //undefined if no Parent.call(this)
console.log(new Child().patchedP); //100
Every function's .prototype property is of type - object except function Function. (It's .prototype property is of type - function)
Every function's .__proto__ property is always equal to Function.prototype and hence of the type - Function.
Objects don't have .prototype property.
Every object's .__proto__ property is of type object.
An object's .__proto__ property takes its value from the .prototype property of the Function from which it was created.
If an object was not created using any particular function (created using object literal or using Object.create(Object.prototype)), the value of it's .__proto__ property will be Object.prototype.
Create an object from a class A or a function A : let objA = Object.create(A.prototype); or let objA = new A();
In ES5, inheritance looks like so : let anObjectFromParent = Object.create(Parent.prototype); Child.prototype = anObjectFromParent;
In ES6, the extends keyword plays the role of Object.create(Parent.prototype) and the super keyword invokes the constructor of the parent.
Accessing __proto__ directly on an object is not as optimal as using the new keyword, Object.create (to set) and Object.getPrototypeOf (to get).
__proto__ is just a way to programmatically access an object's [[Prototype]] internal slot which is otherwise not accessible in code.