28
loading...
This website collects cookies to deliver better user experience
console.log()
the following example, we can see that the prototype is a property:const myObj = {
x: 100,
y: 200,
}
console.log(myObj);
__proto__: Object
, but as shown on the example above there is a value being exposed on the __proto__
, this is the Object.prototype
. But how did that get in there, If you check inside the object we can see other properties and methods that have been inherited by default from the Object.prototype
. This is called the prototype chain. __proto__
which is the link to another object as their prototype. This property inherits all the properties and methods from the object that has been used in the prototype. Let's follow up on the example above.Object.create()
which creates an object and sets the prototype to the object passed as argument. Then set a property of z
to 50
in the newly created object.const myObj = {
x: 100,
y: 200,
}
const anotherObj = Object.create(myObj);
anotherObj.z = 50;
console.log(anotherObj);
__proto__
on the developer tools it's evident that it has correctly inherited the x
and y
properties from the other object. See Image Below.Object.prototype
.Object.protoype
will always be at the top of the prototype inheritance chain, this means that the __proto__
for Object.prototype
is null
.Object.create()
was by using other object as a prototype but there are other ways to create a inherit the prototype of an object.new
keyword.// ES5
function MyObj() {
this.x = 100;
this.y = 200
}
const obj1 = new MyObj();
console.log(obj1)
// ES6
class MyObj {
constructor() {
this.x = 100;
this.y = 200
}
}
const c1 = new MyObj();
console.log(c1);
constructor function
or the constructor()
method in the classfunction MyObj(x, y) {
this.x = x;
this.y = y;
}
MyObj.prototype.sum = function() {
return this.x + this.y;
}
MyObj.call(this, x, y)
function AnotherObj(x,y,z) {
MyObj.call(this, x, y);
this.z = z;
}
function AnotherObj(x,y,z) {
Object.getPrototypeOf(AnotherObj.prototype).constructor.call(this, x ,y)
this.z = z;
}
AnotherObj.prototype = Object.create(MyObj.prototype);
AnotherObj.prototype.constructor = AnotherObj;
const anotherObj1 = new AnotherObj(100, 200, 50);
console.log(anotherObj1);
class MyObj {
constructor() {
this.x = 100;
this.y = 200
}
sum() {
return this.x + this.y;
}
}
super(x,y)
.
class AnotherObj extends MyObj {
constructor(x,y,z) {
super(x,y);
this.z = z;
}
}
const anotherObj1 = new AnotherObj(100, 200, 50);
console.log(anotherObj1)