JavaScript the Fun Part


effective-javascript-2

four-ways-of-creating-an-object (incomplete)


In JavaScript there are more than one way to create an object.

The most common one is Object Literal.

Although at first it seems that we create a variable but in reality we create an object (= instance) that inherits from Object.

// create and object that inherits from Object
const person = {};

// inherited property
person.toString;    // function toString()
person.valueOf;     // function valueOf()

Where is the inherited part? Here

person.prototype

A note here is that if we are going to use a name-pair value just for storing data, we do not need this inheritance.

And for this we can create an object that is truly empty.

// truly empty object
const person = Object.create( null );

person.toString;    // undefined
person.valueOf;     // undefined

This object is completely empty. It does not have any methods.

And if you wonder how it works, here is a quick review.

Object.create() will take a prototype of an object or null. If you pass null then the receiver will not have prototype.

Notice this example:

// using Object.prototype
const o1 = Object.create( Object.prototype );

o1.toString;        // function ...
o1.valueOf;         // function ...

Yes it is strange to us if we have used to create object in this way

// common way of creating an object
const person = new Object();

person.toString;    // function ...
person.valueOf;     // function ...

Here we used Object constructor to create a new object. Also inheritance happens here.


Update: Sun Sep 22 2019 16:46:46 GMT+0330 (Iran Standard Time)