`

JavaScript Primitive Wrapper Types

 
阅读更多

原创转载请注明出处:http://agilestyle.iteye.com/blog/2341689

 

Primitive Wrapper Types

Perhaps one of the most confusing parts of JavaScript is the concept of primitive wrapper types. There are three primitive wrapper types (String, Number, and Boolean). These special reference types exist to make working with primitive values as easy as working with objects. (It would be very confusing if you had to use a different syntax or switch to a procedural style just to get a substring of text.)

The primitive wrapper types are reference types that are automatically created behind the scenes whenever strings, numbers, or Booleans are read. For example, in the first line of this listing, a primitive string value is assigned to name. The second line treats name like an object and calls charAt(0) using dot notation.

var name = "Nicholas";
var firstChar = name.charAt(0);
console.log(firstChar);			// "N"

 

This is what happens behind the scenes:

// what the JavaScript engine does
var name = "Nicholas";
var temp = new String(name);
var firstChar = temp.charAt(0);
console.log(firstChar);			// "N"

 

Because the second line uses a string (a primitive) like an object, the JavaScript engine creates an instance of String so that charAt(0) will work. The String object exists only for one statement before it’s destroyed (a process called autoboxing). To test this out, try adding a property to a string as if it were a regular object:

var name = "Nicholas";
name.last = "Zakas";
console.log(name.last);			// undefined

 

This code attempts to add the property last to the string name. The code itself is just fine except that the property disappears. What happened? When working with regular objects, you can add properties at any time and they stay until you manually remove them. With primitive wrapper types, properties seem to disappear because the object on which the property was assigned is destroyed immediately afterward.

Here’s what’s actually happening in the JavaScript engine: 

// what the JavaScript engine does
var name = "Nicholas";
var temp = new String(name);
temp.last = "Zakas";
temp = null;					// temporary object destroyed
var temp = new String(name);
console.log(temp.last);			// undefined
temp = null;

 

Instead of assigning a new property to a string, the code actually creates a new property on a temporary object that is then destroyed. When you try to access that property later, a different object is temporarily created and the new property doesn’t exist there. Although reference values are created automatically for primitive values, when instanceof checks for these types of values the result is false:

var name = "Nicholas";
var count = 10;
var found = false;
console.log(name instanceof String);	// false
console.log(count instanceof Number);	// false
console.log(found instanceof Boolean);	// false

 

The instanceof operator returns false because a temporary object is created only when a value is read. Because instanceof doesn’t actually read anything, no temporary objects are created, and it tells us the values aren’t instances of primitive wrapper types. You can create primitive wrapper types manually, but there are certain side effects:

var name = new String("Nicholas");
var count = new Number(10);
var found = new Boolean(false);
console.log(typeof name);		// "object"
console.log(typeof count);		// "object"
console.log(typeof found);		// "object"

 

As you can see, creating an instance of the primitive wrapper type just creates another object, which means that typeof can’t identify the type of data you intend to store.

In addition, you can’t use String, Number, and Boolean objects as you would primitive values.

For example, the following code uses a Boolean object. The Boolean object is false, yet console.log(“Found”) still executes because an object is always considered true inside a conditional statement. It doesn’t matter that the object represents false; it’s an object, so it evaluates to true.

var found = new Boolean(false);
if (found) {
	console.log("Found");		// this executes
}

 

Manually instantiating primitive wrappers can also be confusing in other ways, so unless you find a special case where it makes sense to do so, you should avoid it. Most of the time, using primitive wrapper objects instead of primitives only leads to errors.

 

Conclusion

To make primitives seem more like references, JavaScript has three primitive wrapper types: String, Number, and Boolean. JavaScript creates these objects behind the scenes so that you can treat primitives like regular objects, but the temporary objects are destroyed as soon as the statement using them is complete. Although you can create your own instances of primitive wrappers, it’s best not to do that because it can be confusing.

 

Reference

Leanpub.Principles.of.Object-Oriented.Programming.in.JavaScript.Jun.2014

 

分享到:
评论

相关推荐

    Byte-Short-Int-Long-Java-Primitive-Types:字节短整数长Java原语类型

    在Java编程语言中,原生类型(Primitive Types)是其语法结构的基础,它们不依赖于类或接口。本文将深入探讨Java中的四个整数类型:字节(Byte)、短整数(Short)、整数(Integer)和长整数(Long)。理解这些类型...

    JavaScript 教程(CHM格式).rar

    2. 数据类型:JavaScript支持七种数据类型,分为原始类型(Primitive Types)和引用类型(Reference Types)。原始类型包括:Undefined、Null、Boolean、Number、BigInt、String和Symbol。引用类型主要是Object,...

    Cesium撒点封装(Primitive).zip

    Cesium是一个强大的开源JavaScript库,用于在Web上创建交互式的3D地球模型。"Cesium撒点封装(Primitive)"是一个项目,它展示了如何利用Cesium的底层功能来实现高效的点云渲染,这对于地理信息系统(GIS)和大数据...

    JavaScript中的Primitive对象封装介绍

    JavaScript中,string、number、boolean均为primitive基本类型,也即字符串、数值、布尔值并不是以对象的形式而存在的。不过,由于需要对这三种primitive类型值进行操作,因此JavaScript会自动封装这三种类型的值,...

    JavaScript 面试:基本数据型别和参考数据型别 Primitive Data Type & Reference Data Type - 彭彭直播 at 2019/11/18

    JavaScript_面試_基本資料型別和參考資料型別_Primitive_Data_Type_&_Reference_Data

    Javascript.Object.Oriented.Programming.pdf

    Chapter 19: Primitive Data Types, Arrays, Loops, And Conditions Chapter 20: Functions Chapter 21: Objects Chapter 22: Prototype Chapter 23: Inheritance Chapter 24: The Browser Environment Chapter 25: ...

    创建一个字符串的primitive表示

    在JavaScript开发中,"创建一个字符串的primitive表示"这一话题主要涉及到JavaScript中的字符串类型和它的基本操作。在JavaScript中,字符串是不可变的,这意味着一旦创建,就不能改变其内容。以下是一些关于创建和...

    The Principles of Object-Oriented JavaScript 1st Edition

    –The difference between primitive and reference values –What makes JavaScript functions so unique –The various ways to create objects –How to define your own constructors –How to work with and ...

    悟透JavaScript

    JavaScript的数据类型分为两大类:原始类型(Primitive Types)和引用类型(Reference Types)。原始类型包括undefined、null、boolean、number和string,以及在ES6中新增的symbol和BigInt。其中,undefined表示...

    JavaScript 第一章 基本语法 1~3节

    JavaScript有七种数据类型,分为原始类型(Primitive Types)和引用类型(Reference Types)。原始类型包括布尔值(Boolean)、数字(Number)、字符串(String)、空值(null)、未定义(undefined)、Symbol(ES6...

    JAVAScript数据类知识检测.doc

    在JavaScript中,数据类型分为两种:基本数据类型(Primitive Data Types)和引用数据类型(Reference Data Types)。基本数据类型包括Undefined、Null、Boolean、Number、String和ES6新增的Symbol。这些类型在内存...

    JavaScript语言基础.pdf

    JavaScript中有两种主要的数据类型:原始类型(primitive types)和引用类型(reference types)。 - **原始类型**: - 数值(Number)、字符串(String)、布尔值(Boolean)、`null`、`undefined`。 - **引用类型**: - ...

    Sammie Bae - JavaScript Data Structures and Algorithms - 2019.pdf

    and then lays out the basic JavaScript foundations, such as primitive objects and types. Then, this book covers implementations and algorithms for fundamental data structures such as linked lists, ...

    JavaScript基础第01天笔记1

    JavaScript有两种基本数据类型:原始类型(Primitive Types)和引用类型(Reference Types)。原始类型包括布尔值(Boolean)、数字(Number)、字符串(String)、空(Null)、未定义(Undefined)以及ES6引入的...

    头歌教学实践平台 Web前端开发基础 JavaScript 学习手册二:JS 数据类型

    在JavaScript中,数据类型主要分为两大类:基本数据类型(Primitive Data Types)和引用数据类型(Reference Data Types)。基本数据类型包括: 1. **Undefined**:未定义,当变量被声明但未赋值时,其值为...

Global site tag (gtag.js) - Google Analytics