Primitive Wrapper Types

Description

Three special reference types are created for three primitive values:

  • Boolean type
  • Number type
  • String type

The three types act like the other reference types, and have a special behavior for their primitive-type equivalents.

Every time a primitive value is read, an object of the corresponding primitive wrapper type is created assist access to methods for manipulating the data.

Example


var s1 = "hello world";
var s2 = s1.substring(2);
console.log(s2);

s1 is a primitive string value. And substring() method was called on s1 and saved the return value to s2.

Primitive values aren't objects, so they shouldn't have methods. Any time a string value is accessed in read mode, the following three steps occur:

  1. Create an instance of the String type.
  2. Call the specified method on the instance.
  3. Destroy the instance.

For var s2 = s1.substring(2); its actual code is


var s1 = new String("hello world");
var s2 = s1.substring(2);
s1 = null;

Note

In this way the primitive string value acts like an object. Boolean and numeric values have the identical behaviours, respectively.

When you instantiate a reference type using the new operator, it stays in memory until it goes out of scope, whereas automatically created primitive wrapper objects exist for only one line of code.

Properties and methods cannot be added at runtime for primitive types.


var s1 = "hello world";
s1.color = "red";
console.log(s1.color);   //undefined

String object created in the second line is destroyed by the time the third line is called.

The third line creates its own String object, which doesn't have the color property.





















Home »
  Javascript »
    Javascript Introduction »




Script Element
Syntax
Data Type
Operator
Statement
Array
Primitive Wrapper Types
Function
Object-Oriented
Date
DOM
JSON
Regular Expressions