JavaScript Patterns 3.7 Primitive Wrappers
2014-06-03 09:16 小郝(Kaibo Hao) 阅读(311) 评论(0) 编辑 收藏 举报Primitive value types: number, string, boolean, null, and undefined.
// a primitive number var n = 100; console.log(typeof n); // "number" // a Number object var nobj = new Number(100); console.log(typeof nobj); // "object"
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.
// 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"
When used without new, wrapper constructors convert the argument passed to them to a primitive value:
typeof Number(1); // "number" typeof Number("1"); // "number" typeof Number(new Number()); // "number" typeof String(1); // "string" typeof Boolean(1); // "boolean"
作者:小郝
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
出处:http://www.cnblogs.com/haokaibo/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。