HTML and CSS Reference
In-Depth Information
health: 100,
shields: 50,
guns: [{
damage: 20,
speed: 5
damage: 5,
speed: 9000
fire: function() {
console.log(PEW PEW');
var myWayMoreAwesomeShip = ship.manufacture(150);
VoilĂ : you have a ship template that you can build off of, using any given ship as the template.
Of course, there is still one very important question that must be answered: Can you somehow combine these
steps in order to extend the base ship with arbitrary properties?
It turns out that you can do this by writing an extend function and attaching it to all objects. The code for
this is short, but dense:
Object.prototype.extend = function(extendPrototype) {
var hasOwnProperty = Object.hasOwnProperty;
var object = Object.create(this);
for (var property in extendPrototype) {
if(, property) || typeof object[property] ===
'undefined') {
object[property] = extendPrototype[property];
return object;
Whew! There's a lot going on there. Here's what's happening:
You create a function, extend , attached to the base Object .
The function hasOwnProperty checks whether the object has the passed-in property or
whether it's inherited from somewhere else, for example, the base Object .
You create a clone of this ; in the previous example, this would be ship .
Now, you loop through all the properties in the extension; for each property, you perform
these tasks:
You check whether the base Object does not have the given property or whether the
extension has the property directly.
You then you assign the value from the extension to the cloned object.
Once you're done, you return the completed object.
Search WWH ::

Custom Search