JavaScript Patterns 3.7 Primitive Wrappers

Primitive value types: number, string, boolean, null, and undefined.

JavaScript Patterns 3.7 Primitive Wrappers
// a primitive number

var n = 100;

console.log(typeof n); // "number" 


// a Number object

var nobj = new Number(100);

console.log(typeof nobj); // "object" 
JavaScript Patterns 3.7 Primitive Wrappers

One reason to use the wrapper objects is when you want to augment the value and persist state.  Because primitives are not objects, they  cannot be augmented with properties. 

JavaScript Patterns 3.7 Primitive Wrappers
// primitive string

var greet = "Hello there";
 

// primitive is converted to an object

// in order to use the split() method

greet.split(‘ ‘)[0]; // "Hello"
 

// attemting to augment a primitive is not an error

greet.smile = true;
 

// but it doesn‘t actually work

typeof greet.smile; // "undefined" 
JavaScript Patterns 3.7 Primitive Wrappers
When used without new, wrapper constructors convert the argument passed to them to a primitive value:
JavaScript Patterns 3.7 Primitive Wrappers
typeof Number(1); // "number"

typeof Number("1"); // "number"

typeof Number(new Number()); // "number"

typeof String(1); // "string"

typeof Boolean(1); // "boolean"
JavaScript Patterns 3.7 Primitive Wrappers

JavaScript Patterns 3.7 Primitive Wrappers,布布扣,bubuko.com

JavaScript Patterns 3.7 Primitive Wrappers

上一篇:开机黑屏 仅仅显示鼠标 电脑黑屏 仅仅有鼠标 移动 [已成功解决]


下一篇:基于 Android NDK 的学习之旅----- C调用Java