Thursday, May 19, 2011

On the fly JavaScript Casting of Primitive Types Into Objects

I just found out today that NOT everything in JavaScript are objects, I thought they were because if I do something like this:

var a = 10.1234;
var b = a.toFixed(2); // b = 10.12

I used to think that the .toFixed() method was only available on the Number() object and therefore the moment I initialized "a", it had to be a Number() object rather than the native "number" type. That's the only way .toFixed() can be available right?

But turns out, the .toFixed() is only available because we did this
a.toFixed(2);

When we used the dot operator (.) JavaScript internally cast "a" into a Number() object (on the fly) and therefore made the .toFixed() method available.

This is pretty cool I think, but it also can also get pretty complicated.

Here is another example of how the dot operator casts types into objects.

var a = 5;
a.prop = 3;
alert(a.prop); // undefined 

Now in the above example, in line two "a" was cast into an object and "prob" was added to it as a property. But in line three when we tried to alert the new property value it returns 'undefined', this is because in line three the dot operator casts the original "a" into a new object and the object created in line two is now lost.

So there you have it, not everything in JavaScript are objects but internally Javascript casts primitive data types into Objects so that you can get the benefits of useful methods and functions.

Here is more evidence:

var a = 12;
a.constructor.prototype.pi = 25;
alert(a.pi); // returns 25

var c = 30;
alert(c.pi); // returns 25  

So do you know why c.pi returned 25? well, when we did "a.constructor.prototype.pi = 25;", the constructor returned a reference to the internal object function code that cast the "a" variable, in this case "Number()". And we then extended the Number() object using "prototype" to have the new property "pi" and assigned the value 25 to it.

Then when we did "c.pi", "c" was cast into Number() which now had the "pi" property.

Cool huh? hopefully I got this explanation right, please give me your comments if I missed something or you have any other examples.


No comments:

Post a Comment

Fork me on GitHub