首页 > 代码库 > JavaScript Patterns 3.7 Primitive Wrappers
JavaScript Patterns 3.7 Primitive Wrappers
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"
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。