JavaScript Object.assign(), Object.create()

Object.create()

The Object.create() method creates a new object, using an existing object

Demo1

Demo2

Demo3

Object.create(Shape.prototype) is used in the following example for inheritance.

Rectangle.prototype = Object.create(Shape.prototype); line of code overwrite Rectangle.prototype field. So, there were Rectangle constructor in Rectangle.prototype but after overwritten, constructor field will be removed.

So let's see in debug time. Rectangle.prototype has a constructor field which is equal to function Rectangle() as shown in the following screenshot.

I step over the debugger next line and check the value of Rectangle.prototype again. Rectangle.prototype doesn't have a constructor field this time.

Let me show you Rectangle.prototype.__proto__. As shown in the screenshot, there is a function Shape() constructor under __proto__ field.

If you don't set Rectangle.prototype.constructor to Rectangle, it will take the prototype.constructor of Shape (parent). To avoid that, we set the prototype.constructor to Rectangle (child).

Notice that Rectangle.prototype has a constructor named function Rectangle(...)

Find the code below

Object.assign()

Object.assign(target, ...sources);

Demo4

Demo5

Leave a Reply

Your email address will not be published. Required fields are marked *