HTML and CSS Reference
In-Depth Information
obj[funcName].apply(obj,args)
}
};
Although the meat of the function is just a loop over t
his.objects
, the method does have a couple of
interesting JavaScript features.
The first line of the method is a well-known JavaScript hack. The
arguments
object, which is available in
every method call, contains a list of the arguments passed into that method and is used by methods that accept
varying numbers of arguments.
arguments
acts in many ways like an array, but it's not an actual array. This is
a shame because in this case you'd like to get all the arguments out except for the first, which is the
funcName
,
so that they can be passed on to the function to be called on every object.
arguments
doesn't have the slice
method, but because JavaScript enables you to take methods and apply them to whatever object you like using
call
or
apply
, the line
var args = Array.prototype.slice.call(arguments,1);
can do just that and turn the
arguments
object into a proper array starting at the second element. Inside of
the loop the code looks up the method in the object's properties using the square bracket operator and then calls
apply
to call that method with whatever the passed in arguments are.
Next is the detect method, which will be used later for collision detection. Its job is to run the same function
on all of a board's objects and return the first object that the function returns
true
for. In the abstract this
doesn't seem all that useful, but if you need to do collision detection or find a specific object based on certain
parameters, the detect method is useful.
// Find the first object for which func is true
this.detect = function(func) {
for(var i = 0,val=null, len=this.objects.length; i < len; i++) {
if(func.call(this.objects[i])) return this.objects[i];
}
return false;
};
detect
consists of a loop over the objects and a call to the passed-in function with the object passed in as
the
this
context. If that function returns
true
, then the object is returned; otherwise, the functions returns
false
after it runs out of objects to compare against.
Defining the Board Methods
Next are the standard board functions,
step
and
draw
. Using the methods already defined, these functions
have trivial definitions:
// Call step on all objects and then delete
// any objects that have been marked for removal
this.step = function(dt) {
this.resetRemoved();
this.iterate('step',dt);
this.finalizeRemoved();
};