ES6 standardizes the __proto__
property of an object and adds new properties to the global Object
object.
JavaScript objects have an internal [[prototype]]
property that references the object's prototype, that is, the object it inherits. To read the property we had to use Object.getPrototypeof()
and to create a new object with a given prototype we had to use the Object.create()
method. A [[prototype]]
property cannot be directly read or be modified.
Inheriting was cumbersome due to the nature of the [[prototype]]
property, therefore some browsers added a special __proto__
property in objects, which is an accessor property that exposes the internal [[prototype]]
property and makes working with prototypes easier. The __proto__
property was not standardized in ES5 but due to its popularity it was standardized in ES6.
Here is an example to demonstrate this:
//In ES5 var x = {x: 12}; var y = Object.create(x, {y: {value: 13}}); console.log(y.x); //Output "12" console.log(y.y); //Output "13" //In ES6 let a = {a: 12, __proto__: {b: 13}}; console.log(a.a); //Output "12" console.log(a.b); //Output "13"
The Object.is()
method determines whether two values are equal or not. It is similar to the ===
operator but there are some special cases for the Object.is()
method. Here is an example that demonstrates the special cases:
console.log(Object.is(0, -0)); console.log(0 === -0); console.log(Object.is(NaN, 0/0)); console.log(NaN === 0/0); console.log(Object.is(NaN, NaN)); console.log(NaN ===NaN);
Output is:
false true true false true false
The Object.setPrototypeOf()
method is just an another way to assign the [[prototype]]
property of an object. Here is an example to demonstrate this:
let x = {x: 12}; let y = {y: 13}; Object.setPrototypeOf(y, x) console.log(y.x); //Output "12" console.log(y.y); //Output "13"
The Object.assign()
method is used is used to copy the values of all enumerable own properties from one or more source objects to a target object. This method will return the targetObj.
Here is an example which demonstrates this:
let x = {x: 12}; let y = {y: 13, __proto__: x}; let z = {z: 14, get b() {return 2;}, q: {}}; Object.defineProperty(z, "z", {enumerable: false}); let m = {}; Object.assign(m, y, z); console.log(m.y); console.log(m.z); console.log(m.b); console.log(m.x); console.log(m.q == z.q);
Output is:
13 undefined 2 undefined true
Here is a list of important things to keep in mind while using the Object.assign()
method:
[[prototype]]
property of sources.Object.assign()
copies both.Object.getOwnPropertyDescriptor()Object.defineProperty()
instead.null
and undefined
values.18.117.163.50