Object.assign

ECMAscript 6 introduced Object.assign() to achieve this natively in Javascript.

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

The Object.assign() method only copies enumerable and own properties from a source object to a target object.

So first, we create an object called AnimalClass, with properties x, y to denote coordinates of where this animal is. We then have functions move, which literally assigns integers to the x, y properties. Then, locate, which displays where this animal is on a coordinate.

We then use Object.create to create an empty object called target. The target’s prototype is this AnimalClass. This means that whatever property or function gets appended to target, its prototype is always AnimalClass. This is so that you can inherit AnimalClass’s functionalities on this object.


— target —
{}
{ x: 0, y: 0, locate: [Function: locate], move: [Function: move] }
I’m here: 0, 0

Creating a duck via Object.assign

Now that we have a target object, what we’re trying to do is to copy all the properties and functionalities of source object(s) into this target object. Hence we define a custom anonymous object where we add property “color” and function “speak”.

It returns an object, and we test the inheritance by using its own properties, and its prototype’s functionalities.


output:

— duck —
{ color: ‘black’, speak: [Function: speak] }
true
black
quack quack
I’m here: 7, 8