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)

扫描二维码关注公众号,回复: 339532 查看本文章

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 

 

 

 

猜你喜欢

转载自agilestyle.iteye.com/blog/2341585