Java Reference
In-Depth Information
value: function() {
var object =
Object.create(Object.getPrototypeOf(this));
object.mixin(this);
return object;
}
})
Now we can create a clone of superman :
var bizarro = superman.copy();
bizarro.name = "Bizarro";
<< "Bizarro";
bizzaro.realName = "Subject B-0";
<< "Subject B-0"
Note that this is a deep copy and isn't copied by reference, so any subsequent changes to
the superman or bizzaro objects will not affect the other.
Using the Mixin Method to Add Modular Functionality
The prototypal inheritance model allows us to add functionality to objects by inheriting
properties and methods from other objects. While this is useful, it can be undesirable to cre-
ate a chain of inheritance―sometimes we just want to add properties and methods without
linking the two objects together. The mixin() method lets us encapsulate properties and
methods in an object, and then add them to other objects without the overhead of an inher-
itance chain being created.
One way to think about the difference between inheritance from prototype objects and in-
heritance from mixin objects is to consider whether an object is something or whether it
has something. For example, a tank is a vehicle, so it might inherit from a Vehicle pro-
totype object. The tank has a gun, so this functionality could be added using a gun mixin
object. This gives us extra flexibility since other objects might also use a gun but not be a
vehicle, such as a soldier object, for example. The soldier object might inherit from
a Human prototype object but also have the gun mixin.
Search WWH ::




Custom Search