Tuesday 26 July 2011

Auto-boxing JavaScript primitive types

Primitive Types in JavaScript

Number values, like 1,
string values, like "",
the boolean values true and false,
and the special values null and undefined

Object types in JavaScript

Date objects,
regular expression objects,
function objects,
arrays
and literal objects like {}

Auto-boxing
Whenever you access or assign to a property of a number, string or boolean, a temporary object value (of the Number, String or Boolean class, respectively) is created with the same naked value as the primitive value, but that temporary object is only available to that property access, and does not replace the primitive value that your variable references.

Example

Calling split() on primitive value.


var str = 'primitive-valued string literal';
console.log( str.split(' ') ); //=> obviously ["primitive-valued", "string", "literal"]
str.split = function(){ return 'overridden!'; };
console.log( str.split(' ') ); //=> still ["primitive-valued", "string", "literal"]


Calling split() on String object.


var str = new String( 'primitive-valued string literal' );
console.log( str.split(' ') ); //=> obviously ["primitive-valued", "string", "literal"]
str.split = function(){ return 'overridden!'; };
console.log( str.split(' ') ); //=> "overridden!" that's more like it


Read more >>

1 comment:

  1. Awesome! I've been trying to understand boxing in Javascript for a while. Thanks very much!

    Rick

    ReplyDelete