How do you make a stricter script? You maybe wondering... but because JavaScript can be so forgiving at times, you might want to put this into your code manually...
A simple example would be:-
function whatever(a,b,c)
{
if(a == undefined)
Abort("'a' is undefined in whatever");
if(b == undefined)
Abort('"b' is undefined in whatever");
if(c == undefined)
Abort("'c' is undefined in whatever");
}
Well, right now I'm thinking that looks like way too much effort.. Are you?
Wouldn't it be helpful if we just checked all the parameters of the function using an array?
Well, actually we can do that...
function whatever(a,b,c)
{
for(var i = 0; i < whatever.arguments.length; ++i)
if(whatever.arguments[i] == undefined)
Abort(whatever.arguments[i] + " is undefined in whatever");
}
What if you pass too many paramters into the function? Or too little parameters?
Well, you can check the number of actual parameters that are defined against the header of the function...
whatever.arity should be 3, or there isn't the right amount of paramters...
function whatever(a,b,c)
{
if(whatever.arity != whatever.arguments.length)
Abort("whatever called with incorrect number of parameters...");
}
Now, we move onto some more complex methods of idiot proofing your scripts...
You can check the type of the parameters...
if(typeof(a) != typeof(0)) Abort("'a' is not a number");
Other types to test are:-
function, String, Number, Boolean, Array and Object..
This means that:-
whatever(["x","y","z"],b,c) will fail... Because you've passed in an Array instead of a number. Heh, opps, silly you...
Bah, for the hell of it I'll throw in what something that looks this:-
e = (a ? b : c)
... does...
e is equal to b, if a is true, otherwize, e is equal to c.
A different way of writing that is:-
e = a ? b : c
E.g:
this.x = x ? x : 0;
Although for that...
this.x = (typeof(x) == typeof(0)) ? x : 0;
Would be better, because it makes more sense.
Thats it! Happy coding!!
Thats its folks, soon, I will cover *whatever* anyone wants me to..
|