HTML and CSS Reference
In-Depth Information
Reread that a few times if you need to; it's a lot to digest. Now that you know the steps, however, you can create a
new ship template, with any additional property changes you want, as shown:
var newShipModel = ship.extend({
health: 200,
shields: 100,
fire: function() {
console.log('TRIPLE PEW!!!');
}
});
You can think of this as a new model of ship that you're going to have your shipyards build:
var oldShip = ship.manufacture(100);
var newShip = newShipModel.manufacture(150);
this
You may be a little confused by the use of the this keyword in the prior extend function. this behaves somewhat
differently in JavaScript than it does in many other languages, primarily because JavaScript is not a class-based language.
this can behave differently, depending on where it's called, and can even change from function call to function
call in the same function.
Let's walk through the different values this can take on:
If you call
this globally, then it refers to the global object, which is the window object, if
running inside a browser.
If you call
this inside a function that is not attached to an object, this refers to the global
object, because, by default, functions are attached to the global object.
If you call
this inside a function that is attached to an object, such as in the fire method of
ship , then it refers to the object the function is attached to (in this case, ship ).
If you call
this inside a constructor function, then a new object is created when you call it with
new , and this refers to that object.
If you call
this in a function that is then called from an event handler, then this refers either
to the document object model (DOM) element in the page that triggered the event or to the
global object, if there is no such DOM element.
Note that this last value is where you're most likely to run into trouble, because the behavior concerning event
handlers specifically overrides the behavior you would otherwise expect.
Fortunately, you can get around some of this behavior with the call and apply functions. These are attached
to every function object and are used to explicitly set what this refers to. For instance, if you called myAwesomeShip.
fire.call(myMoreAwesomeShip) , then this would refer to myMoreAwesomeShip .
In general, it's useful to explicitly declare what you expect this to be whenever you call a function that uses it.
often, developers coming from a class-based oop language rail against the lack of proper oop in JavaScript.
the truth is that JavaScript has a very flexible oop model that can be used in much the same way as a more classical
language if required. if you don't need it, then the flexibility of JavaScript's prototypical inheritance can actually be a huge
boon, making it far simpler to build up the complex inheritances necessary for a game.
Note
 
 
Search WWH ::




Custom Search