jcompagner wrote:
That example is what i gave to give you a piece of code why i think instanceof should work on that..
Because you can call all methods of that Number type you check for on it!
So purely looking at myNumber from a higher point of view it is a Number ...
It doesn't really matter how you declared it..jbader wrote:PS you do realize how hard this makes explicit type checking and assertions in unit testing right?
No not really can you give me an example why it makes it hard?
But i tested some more and came to a conclusion that some pieces of javascript are just weird:
- Code: Select all
var x = true
var y = true
alert(x == y); // TRUE
var x = new Boolean(true)
var y = true
alert(x == y); // TRUE
var x = true
var y = new Boolean(true)
alert(x == y); // TRUE
var x = new Boolean(true)
var y = new Boolean(true)
alert(x == y); // FALSE?????
that is just weird...
I see your point about number vs Number in the example we both gave. What is the point afterall in having the primitive at all if you can use the Number object's properties and methods on the fly without an exception being thrown. I certainly would agree that makes even having a primitive fairly useless. But the fact is that it is there and that is just how it works.
Regarding an example of why it makes explicit type checking dificult consider...
- Code: Select all
/**
* Do something.
*
* @param {number} n A number primitive.
*
*/
function doSomething(n) {
// Explicit type checking
if(typeof(n) !== 'number') {
throw new TypeError('N must be of type number.');
}
else {
// Turn off the city's powergrid.
}
}
In the above example if n were defined as follows in scripting...
- Code: Select all
var n = 10;
Then the result of typeof above would be 'number' and the city's powergrid would be turned off.
If however it were defined as follows (also in scripting)...
- Code: Select all
var n = new Number(10);
Then the result of typeof above would be 'object' and the city's powergrid would not be turned off.
Now if the parameter n were passed into the function from Servoy's Java code/not defined in scripting it would in fact be a Number object, but would also pass the typeof check(!) b/c from what I can tell you have somehow made n both Number and number.
So you might be thinking well sure, but who cares at the end of the day it's the number 10...and yeah, you are right, but the fact is I can't explicitly check it and determine what it really is.
Finally regarding all of the other examples the trouble with those are that you are checking falsy and truthy values, which you should never do in JS unless you mean to. The general rule is to ALWAYS use === unless you are purposely checking all falsy or truthy (or so says Crockford). In JS truthy and falsy values are strange indeed. Change your '==' to '===' and everything will change.