HTML and CSS Reference
In-Depth Information
The biggest thing to watch out for is that, whereas the empty string is false , the empty object is true . Be aware of
this when using objects in comparisons, and you'll have solved 90 percent of your problems with truthiness.
Inheritance the JavaScript Way
If you're coming from traditional game development, you're probably very familiar with object-oriented programming
(OOP) and specifically, class-based OOP, the model that C++ and Java use.
JavaScript uses a different OOP model, prototypical inheritance, which is derived from self 's object model.
I'll close out this chapter by discussing what prototypical inheritance is and how to use it instead of the more
classical inheritance you may be used to.
Prototypical Inheritance
Prototypical inheritance, at its core, is concerned with only two things:
1.
How do you create a new object?
2.
How do you extend a new object from an existing one?
Creating a bare new object is simple, using object literal notation. Let's say you wanted to create the following ship:
var myAwesomeShip = {
health: 100,
shields: 50,
guns: [{
damage: 20,
speed: 5
},{
damage: 5,
speed: 9000
}],
fire: function() {
console.log('PEW PEW');
}
};
Simple enough. But, what if you wanted to create a new ship, using myAwesomeShip as a template, but with
better shields? Obviously, you could just copy and paste things, but that's no good. Instead, you can create a clone of
myAwesomeShip , using prototypical inheritance, like so:
var myMoreAwesomeShip = Object.create(myAwesomeShip);
myMoreAwesomeShip.shields = 100;
And, you're done. Now, if you wanted, you could roll this into a ship template object, as follows:
var ship = {
manufacture: function(shields) {
var newShip = Object.create(this);
newShip.shields = shields;
return newShip;
},
 
Search WWH ::




Custom Search