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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
var AnimalClass = { x: 0, y: 0, locate : function() { console.log("I'm here: " + this.x + ", " + this.y) }, move: function(x, y) { this.x = this.x + x; this.y = this.y + y; } } var target = Object.create(AnimalClass); console.log("--- target ---") console.log(target); // target itself is always empty console.log(target.__proto__) // its prototype will be of animal target.locate() |
— 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
console.log("--- duck ---") var daffy = Object.assign(target, { // properties here is appended to target // the prototype of the returned object is target.__proto__ color : "black", speak : function() { console.log("quack quack"); } }); console.log(daffy) console.log(daffy.__proto__ === target.__proto__) console.log(daffy.color) daffy.speak() daffy.move(7, 8) daffy.locate(); |
output:
— duck —
{ color: ‘black’, speak: [Function: speak] }
true
black
quack quack
I’m here: 7, 8