01.31.05

An Object By Any Other Name Would Still Do What?

Posted in Uncategorized at 11:05 am by UnwashedMeme

We’ve been programming in Javascript for a little bit now. My current favorite
feature of Javascript is its wonderful behavior of “Everything is an Object,
unless it isn’t.” If the language were to do automatic boxing and unboxing I
think it would work out a lot better.

One place this is an issue is when dealing with the ‘if’ construct,
as Russ previously
mentioned
. The key thing to remember is that it is just an ’isNull’
check.

var s = new String(”")
var n = new Number(0)
var a = new Array()
if(”") print(’foo’); else print(’bar’);
bar
if(s) print(’foo’); else print(’bar’);
foo
if(0) print(’foo’); else print(’bar’);
bar
if(n) print(’foo’); else print(’bar’);
foo
if([]) print(’foo’); else print(’bar’);
foo
if(a) print(’foo’); else print(’bar’);
foo

If you found the last one confusing, remember that Array is not a primitive
type in Javascript, it is always an object. The [] is just some syntactic
sugar.  Once you know all of this it isn’t to bad, just not very clear.

It is also annoying when you want to know where to call a function. Is it a
property of the object or just some disembodied function elsewhere.

new Number(NaN).isNaN()
TypeError: (new Number(NaN)).isNaN is not a function
isNaN(NaN)
true
isNaN(new Number(NaN))
true
NaN == NaN
false 
typeof(NaN)
number

So NaN is a bit of a special case, but in my experience so far Javascript has a
number of these quirks.

I haven’t seen very much good writing about prototypical inheritence. Mathew
Morgan put together some good information about
Programming with Prototypes
.

Leave a Comment