wrapper objects

Description

We can create the primitive wrapper objects using the Boolean, Number, and String constructors.

Calling typeof on an instance of a primitive wrapper type returns "object"

All primitive wrapper objects convert to the Boolean value true.

Object constructor

Object constructor acts as a factory method and can return an instance of a primitive wrapper based on value passed in. For example:

  • When a string is passed into the Object constructor, an instance of String is created.
  • When a number is passed into the Object constructor, an instance of number is created.
  • When a Boolean is passed into the Object constructor, an instance of Boolean is created.

var obj = new Object("hi");
console.log(obj instanceof String);   //true

The code above generates the following result.

Note

Calling a primitive wrapper constructor using new is not the same as calling the casting function of the same name. For example:


var value = "5";
var number = Number(value);   //casting function
console.log(typeof number);   //"number"
/* w ww  . jav  a 2  s.  c  o  m*/
var obj = new Number(value);    //constructor
console.log(typeof obj);              //"object"

In this example, number is filled with a primitive number value of 5 while the variable obj is filled with an instance of Number.

The code above generates the following result.





















Home »
  Javascript »
    Javascript Introduction »




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