`

JavaScript Primitive and Reference Types

 
阅读更多

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

 

Although JavaScript has no concept of classes, it still uses two kinds of types: primitive and reference.

Primitive types are stored as simple data types.

Reference types are stored as objects, which are really just references to locations in memory.

 

Primitive Types

Primitive types represent simple pieces of data that are stored as is, such as true and 25.

There are five primitive types in JavaScript:

Boolean - true or false

Number - Any integer or floating-point numeric value

String - A character or sequence of characters delimited by either single or double quotes(JavaScript has no separate character type)

Null - A primitive type that has only one value, null.

Undefined - A primitive type has only one value, undefined (undefined is the value assigned to a variable that is not initialized)

// strings
var name = "JS";
var selection = "a";

// numbers
var count = 25;
var cost = 1.51;

// boolean
var found = true;

// null
var object = null;

// undefined
var flag = undefined;
var ref;    // assigned undefined automatically

 

Each variable containing a primitive value uses its own storage space, changes to one variable are not reflected on the other.

var color1 = "red";
var color2 = color1;

console.log(color1);    // "red"
console.log(color2);    // "red"

color1 = "blue";
console.log(color1);    // "blue"
console.log(color2);    // "red"

 

Identifying Primitive Types

The best way to identify primitive types is with the typeof operator, which works on any variable and returns a string indicating the type of data.

console.log(typeof "Nicholas"); // "string"
console.log(typeof 10);         // "number"
console.log(typeof 5.1);        // "number"
console.log(typeof true);       // "boolean"
console.log(typeof undefined);  // "undefined"

 

When you run typeof null, the result is “object”. But why an object when the type is null? (In fact, this has been acknowledged as an error by TC-39, the committee that designs and maintains JavaScript. You could reason that null is an empty object pointer, making “object” a logical return value, but that’s still confusing.)

console.log(typeof null);       // "object"

 

The best way to determine if a value is null is to compare it against null directly, like this:

console.log(value === null);    // true or false

 

Comparing Without Coercion

Notice that this code uses the triple equals operator (===) instead of the double equals operator.

The reason is that triple equals does the comparison without coercing the variable to another type. To understand why this is important, consider the following:

console.log("5" == 5);              // true
console.log("5" === 5);             // false
console.log(undefined == null);     // true
console.log(undefined === null);    // false

When you use the double equals, the string “5” and the number 5 are considered equal because the double equals converts the string into a number before it makes the comparison. The triple equals operator doesn’t consider these values equal because they are two different types. Likewise, when you compare undefined and null, the double equals says that they are equivalent, while the triple equals says they are not. When you’re trying to identify null, use triple equals so that you can correctly identify the type. 

 

Primitive Methods

Despite the fact that they're primitive types, strings, numbers, and Booleans actually have methods. (The null and undefined types have no methods.) Strings, in particular, have numerous methods to help you work with them. 

var name = "JavaScript";
var lowercaseName = name.toLowerCase();     // convert to lowercase
var firstLetter = name.charAt(0);           // get first character
var middleOfName = name.substring(2, 5);    // get characters 2-4
var count = 10;
var fixedCount = count.toFixed(2);          // convert to "10.00"
var hexCount = count.toString(16);          // convert to "a"
var flag = true;
var stringFlag = flag.toString();           // convert to "true"

Note:

Despite the fact that they have methods, primitive values themselves are not objects. JavaScript makes them look like objects to provide a consistent experience in the language. 

 

Reference Types

Reference types represent objects in JavaScript and are the closest things to classes that you will find in the language. Reference values are instances of reference types and are synonymous with objects.

 

Creating Objects

When you assign an object to a variable, you're actually assigning a pointer. That means if you assign one variable to another, each variable gets a copy of the pointer, and both still reference the same object in memory. For example:

var object1 = new Object();
var object2 = object1;

 

Dereferencing Objects

JavaScript is a garbage-collected language, so you don’t really need to worry about memory allocations when you use reference types. However, it’s best to dereference objects that you no longer need so that the garbage collector can free up that memory. The best way to do this is to set the object variable to null.

var object1 = new Object();
// do something
object1 = null; // dereference

 

Adding or Removing Properties

Another interesting aspect of objects in JavaScript is that you can add and remove properties at

any time. For example:

var object1 = new Object();
var object2 = object1;

object1.myCustomeProperty = "Awesome!";

console.log(object2.myCustomeProperty);     // "Awesome!"

Here, myCustomProperty is added to object1 with a value of "Awesome!". That property is also accessible on object2 because both object1 and object2 point to the same object. 

Note:

This example demonstrates one particularly unique aspect of JavaScript: You can modify objects whenever you want, even if you didn’t define them in the first place. Also there are ways to prevent such modifications.

 

Instantiating Built-in Types

The Object type is just one of a handful of built-in reference types that JavaScript provides. The other built-in types are more specialized in their intended usage and can be instantiated at any time.

The built-in types are:

Array - An ordered list of numerically indexed values

Date - A date and time

Error - A runtime error (there are also several more specific

Function - A function

Object - A generic object

RegExp - A regular expression

 

You can instantiate each built-in reference type using new, as shown here:

var items = new Array();
var now = new Date();
var error = new Error("Something bad happened.");
var func = new Function("console.log('Hi');");
var object = new Object();
var re = new RegExp("\\d+");

 

Literal Forms

Several built-in reference types have literal forms. A literal is syntax that allows you to define a reference value without explicitly creating an object, using the new operator and the object's constructor.

Object Literals

To create an object with object literal syntax, you can define the properties of a new object inside braces. Properties are made up of an identifier or string, a colon, and a value, with multiple properties separated by commas.

For example:

var book = {
    name: "The Principles of Object-Oriented JavaScript",
    year: 2014
};

 

You can also use string literals as property names, which is useful when you want a property

name to have spaces or other special characters:

var book = {
    "name": "The Principles of Object-Oriented JavaScript",
    "year": 2014
};

 

This example is equivalent to the previous one despite the syntactic differences. Both examples are also logically equivalent to the following: 

var book = new Object();
book.name = "The Principles of Object-Oriented JavaScript";
book.year = 2014;

 

The outcome of each of the previous three examples is the same: an object with two properties.

The choice of pattern is up to you because the functionality is ultimately the same.

Note:

Using an object literal doesn’t actually call new Object(). Instead, the JavaScript engine follows the same steps it does when using new Object() without actually calling the constructor. This is true for all reference literals.

 

Array Literals

You can define an array literal in a similar way by enclosing any number of comma-separated values inside square brackets. For example:

var colors = [ "red", "blue", "green" ];
console.log(colors[0]); // "red"

 

This code is equivalent to the following:

var colors = new Array("red", "blue", "green")
console.log(colors[0]); // "red"

 

Function Literals

You almost always define functions using their literal form. In fact, using the Function constructor is typically discouraged given the challenges of maintaining, reading, and debugging a string of code rather than actual code, so you'll rarely see it in code.

Creating functions is much easier and less error prone when you use the literal form. For example:

function reflect(value) {
    return value;
}

 

This code is equivalent to the following:

var reflect = new Function("value", "return value;");

This code defines the reflect() function, which returns any value passed to it. Even in the case of this simple function, the literal form is easier to write and understand than the constructor form.

Further, there is no good way to debug functions that are created in the constructor form:

These functions aren’t recognized by JavaScript debuggers and therefore act as a black box in your application. 

 

Regular Expression Literals

The pattern is contained between two slashes, and any additional options are single characters following the second slash. For example:

var numbers = /\d+/g;

 

This code is equivalent to the following: 

var numbers = new RegExp("\\d+", "g");

The literal form of regular expressions in JavaScript is a bit easier to deal with than the constructor form because you don’t need to worry about escaping characters within strings.When using the RegExp constructor, you pass the pattern in as a string, so you have to escape any backslashes. (That’s why \d is used in the literal and \\d is used in the constructor.) Regular expression literals are preferred over the constructor form in Java Script except when the regular expression is being constructed dynamically from one or more strings. 

 

Property Access

Properties are name/value pairs that are stored on an object. Dot notation is the most common way to access properties in JavaScript (as in many object-oriented languages), but you can also access properties on JavaScript objects by using bracket notation with a string.

For example, you could write this code, which uses dot notation:

var array = [];
array.push(12345);

 

With bracket notation, the name of the method is now included in a string enclosed by square brackets, as in this example:

var array = [];
array["push"](12345);

 

This syntax is very useful when you want to dynamically decide which property to access. For example, here bracket notation allows you to use a variable instead of the string literal to specify the property to access. 

var array = [];
var method = "push";
array[method](12345);

In this listing, the variable method has a value of "push", so push() is called on the array. The point to remember is that, other than syntax, the only difference - performance or otherwise - between dot notation and bracket notation is that bracket notation allows you to use special characters in property names.

Developers tend to find dot notation easier to read, so you'll see it used more frequently than bracket notation.

 

Identifying Reference Types

A function is the easiest reference type to identify because when you use the typeof operator on a function, the operator should return "function":

function reflect(value) {
    return value;
}
console.log(typeof reflect);    // "function"

Other reference types are trickier to identify because, for all reference types other than functions, typeof returns "object". That's not very helpful when you're dealing with a lot of different types. To identify reference types more easily, you can use JavaScript's instanceof operator.

The instanceof operator takes an object and a constructor as parameters. When the value is an instance of the type that the constructor specifies, instanceof returns true; otherwise, it returns false, as you can see here: 

var items = [];
var object = {};
function reflect(value) {
    return value;
}
console.log(items instanceof Array);        // true
console.log(object instanceof Object);      // true
console.log(reflect instanceof Function);   // true

 

The instanceof operator can identify inherited types. That means every object is actually an instance of Object because every reference type inherits from Object.

var items = [];
var object = {};
function reflect(value) {
    return value;
}
console.log(items instanceof Array);        // true
console.log(items instanceof Object);       // true
console.log(object instanceof Object);      // true
console.log(object instanceof Array);       // false
console.log(reflect instanceof Function);   // true
console.log(reflect instanceof Object);     // true

 

Identifying Arrays

The Array.isArray() method is supported in most environments, both in browsers and in Node.js. This method isn't supported in Internet Explorer 8 and earlier.

var items = [];
console.log(Array.isArray(items)); // true

 

 

Reference

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

 

 

 

分享到:
评论

相关推荐

    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.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: ...

    JavaScript 教程(CHM格式).rar

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

    悟透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权威指南(第六版)

    3.7 Immutable Primitive Values and Mutable Object References 44 3.8 Type Conversions 45 3.9 Variable Declaration 52 3.10 Variable Scope 53 4. Expressions and Operators . . . . . . . . . . . . . . . . ...

    JavaScript基础第01天笔记1

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

    JavaScript语言基础.pdf

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

    javascript学习

    JavaScript有七种基本数据类型,分为原始类型(Primitive Types)和引用类型(Reference Types)。原始类型包括:Undefined、Null、Boolean、Number、BigInt、String和Symbol。常量,也称为字面量,是直接赋值的不...

    JAVAScript数据类知识检测.doc

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

    2021javascript面试题.docx

    其中,Number 和 String 是primitive types,其他都是reference types。 2. null 和 undefined 的区别:null 表示一个对象的值为空,undefined 表示一个变量或对象属性不存在或没有赋值。 3. JavaScript 变量声明:...

    javascript相关知识20190723.zip

    JavaScript支持两种主要的数据类型:基本类型(Primitive Types)和引用类型(Reference Types)。基本类型包括字符串(String)、数字(Number)、布尔值(Boolean)、null、undefined和Symbol(ES6新增)。而引用...

    Beginning.JavaScript

    - 原始类型(primitive types):`number`、`string`、`boolean`、`null`、`undefined`、`symbol`。 - 引用类型(reference types):`object`、`array`、`function`等。 3. **运算符**:JavaScript提供了丰富的...

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

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

    JavaScript 24道面试题和答案.docx

    - JavaScript中有两种主要的数据类型:基本数据类型(Primitive Types)和引用数据类型(Reference Types)。 - 基本数据类型包括Undefined、Null、Boolean、Number、String、Symbol(ES6新增)。 - 引用数据类型...

    html5前端基础之JavaScript基础

    JavaScript有七种数据类型:**原始类型**(Primitive Types)包括`null`、`undefined`、`boolean`、`number`、`bigint`、`string`和`symbol`,以及**引用类型**(Reference Type)`object`。其中,`null`和`...

    JavaScript试题集

    - JavaScript中的数据类型分为原始类型(primitive types)和引用类型(reference types)。 - **原始类型**包括:`number`、`string`、`boolean`、`null`、`undefined`。 - **引用类型**包括:`object`(包括`...

    1902_陈良鑫_01JavaScript数据类型.docx

    #### 基本数据类型(Primitive Types) - **String**: 表示文本,如`"hello"`。 - **Number**: 表示数字,如`42`、`3.14`。 - **Boolean**: 表示逻辑值,只有`true`和`false`两种状态。 - **Null**: 特殊的空值类型,...

Global site tag (gtag.js) - Google Analytics