码迷,mamicode.com
首页 > 移动开发 > 详细

JavaScript Patterns 3.7 Primitive Wrappers

时间:2014-06-03 16:20:47      阅读:345      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

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

bubuko.com,布布扣
// a primitive number

var n = 100;

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


// a Number object

var nobj = new Number(100);

console.log(typeof nobj); // "object" 
bubuko.com,布布扣

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. 

bubuko.com,布布扣
// 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" 
bubuko.com,布布扣
When used without new, wrapper constructors convert the argument passed to them to a primitive value:
bubuko.com,布布扣
typeof Number(1); // "number"

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

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

typeof String(1); // "string"

typeof Boolean(1); // "boolean"
bubuko.com,布布扣

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

JavaScript Patterns 3.7 Primitive Wrappers

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/haokaibo/p/primitive-wrappers.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!