首页 > 移动平台 > 详细

JavaScript Patterns 3.7 Primitive Wrappers

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

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!