Here is simple example:
The code doesn’t work, because
rect in a plain object, which doesn’t contains any behavior. Someone called the rect
DTO, Data Transfer Object, or POJO, Plain Old Java Object, a concept borrowed from Java world. Here we call it
To add behaviors to
DTO, there are variant approaches. Such as create a behavior wrapper around the
DTO, or create a new model with behavior and copy all the data from
DTO to model. These practices are borrowed from Java world, or traditional Object Oriented world.
Object Mutation, altering object prototype chain on the fly to convert a object into the instance of a specific type. The process is really similar to biologic genetic mutation, converting a species into another by altering the gene, so I borrow the term
With the idea, we can achieve this:
The key to implement
mutate function is to simulate
new operator behavior, alerting
object.__proto__ and apply
constructor to the instance! For more detail, check out the library mutator , which is available as both
NPM package and
When implementing the
object.__proto__ in IE 10 and prior. The most similar workaround is doing a hard-copy of all the members, but it still fails in type check and some dynamical usage.
object.__proto__is a Mozilla “private” implementation until EcmaScript 6.
Luckily, IE 11 introduced some features in EcmaScript 6,
object.__proto__is one of them.