Java Reference
In-Depth Information
Mixins
A mixin method is a way of adding properties and methods of some objects to another object
without using inheritance. It allows more complex objects to be created by “mixing” ba-
sic objects together. Below is a basic mixin method that is added as a property of the Ob-
ject.prototype object. This means that every object will inherit this method and be
able to use it to augment itself with the properties and methods from other objects:
Object.defineProperty(Object.prototype, 'mixin', {
enumerable: false,
writable: false,
configurable: false,
value: function(object) {
for (var property in object) {
if (object.hasOwnProperty(property)) {
this[property] = object[property];
}
}
return this;
}
});
This appears to work as expected:
a = {};
<< {}
b = { name: "JavaScript" };
<< { name: "JavaScript" }
a.mixin(b);
<< { name: "JavaScript" };
There is a problem with this method, however. If any of the properties being mixed in are
arrays or nested objects, only a shallow copy is made, which can cause a variety of issues
(see note).
Search WWH ::




Custom Search