The JavaScript Programming Language

Wrapper Object

Strings, numbers and booleans are not objects. But if we want to implement some operation (method) to them they are converted temporary into 'wrapper object'.

Then method perform some operation and finally the wrapper object is destroyed.

 

 

var s, o;

s = 'Some string';

s.replace('Some', 'Replaced');  //String wrapper object is created, perform replace() method and wrapper is destroyed

 

 

 

Wrapper object apper only when we try to read property or use some method.

It is not possible to assign (set) new property because strings, numbers and booleans are not objects.

That's why s.len = 4; in the next example will not work.

 

057wrapper_object.js

/* s.len=4 will not work because s is string not object*/

var s = "test"; //this is string

s.len = 4; //setting a property will not take an effect

var t = s.len;
console.log(t); //returns undefined because s.len=4 doent work

 

String, number, and boolean values differ from objects becuse their properties are read-only and that you can’t define new properties on them.

 

CONCLUSION:

a) Wrapper objects are temporary objects (will be automatically deleted by JS engine)

b) Wrapper objects are created when we want to apply some method on string, number or boolean (primitive data type)

c) Wrapper objects are created when we want to read property of the string, number or boolean. For example str.length .

d) It is not possible to add new property to string, number or boolean. For example: str.my_property .

e) It is not possible to modify existing string properties. For example: str.length = 2  

 

(Example: 058wrapper_object_readonly.js)

var s = "test"; //this is string with length = 4

s.length = 2; //this will not take effect because string property is read only

console.log(s.length); //4