New version of this blog post: inside “ECMAScript 6: new OOP features besides classes”.
Copying all properties of one object to another one is a common operation in JavaScript. This blog post explains ECMAScript 6’s implementation of it, which is called Object.assign().
This merging operation has a name in the JavaScript ecosystem that is only used there (and, unfortunately, clashes with classic OOP terminology): “extend”. Two examples of “extend” being provided by libraries:
Object.assign(target, source_1, ..., source_n)This function modifies target and returns it: it first copies all enumerable [1] own operties of source_1 to target, then those of source_2, etc.
class Point { constructor(x, y) { this.x = x; this.y = y; } }My favorite would have been the following syntax to completely remove that redundancy (CoffeeScript and TypeScript both have ways of doing this, but I prefer this syntax):
class Point { constructor(this.x, this.y) { } }Object.assign() at least enables you to avoid some of the redundancy:
class Point { constructor(x, y) { Object.assign(this, { x, y }); } }In ECMAScript 6, { x, y } is an abbreviation for { x: x, y: y }.
MyClass.prototype.foo = function (arg1, arg2) { ... };ECMAScript 6 has a more concise syntax for methods [3]. Thanks to Object.assign(), you don’t have to abandon that syntax:
Object.assign(MyClass.prototype, { foo(arg1, arg2) { ... } });
var copy = Object.assign({ __proto__: obj.__proto__ }, obj);If you are only interested in an object’s own properties, things become simpler:
var copy = Object.assign({}, obj);