Built-in objects

Earlier in this chapter, you came across the Object() constructor function. It's returned when you create objects with the object literal notation and access their constructor property. Object() is one of the built-in constructors; there are a few others, and in the rest of this chapter you'll see all of them.

The built-in objects can be divided into three groups:

  • Data wrapper objects: These are Object, Array, Function, Boolean, Number, and String. These objects correspond to the different data types in JavaScript. There is a data wrapper object for every different value returned by typeof (discussed in Chapter 2, Primitive Data Types, Arrays, Loops, and Conditions), with the exception of undefined and null.
  • Utility objects: These are Math, Date, and RegExp, and can come in handy.
  • Error objects: These include the generic Error object as well as other more specific objects that can help your program recover its working state when something unexpected happens.

Only a handful of methods of the built-in objects will be discussed in this chapter. For a full reference, see Appendix C, Built-in Objects.

If you're confused about what a built-in object is and what a built-in constructor is, well, they are the same thing. In a moment, you'll see how functions and, therefore, constructor functions, are also objects.

Object

Object is the parent of all JavaScript objects, which means that every object you create inherits from it. To create a new empty object, you can use the literal notation or the Object() constructor function. The following two lines are equivalent:

    > var o = {}; 
    > var o = new Object(); 

As mentioned before, an empty (or blank) object is not completely useless, because it already contains several inherited methods and properties. In this book, empty means an object like {} that has no properties of its own, other than the ones it automatically gets. Let's look at a few of the properties that even blank objects already have:

  • The o.constructor property returns a reference to the constructor function
  • The o.toString() is a method that returns a string representation of the object
  • The o.valueOf() returns a single-value representation of the object; often, this is the object itself

Let's see these methods in action. First, create an object:

    > var o = new Object(); 

Calling toString() returns a string representation of the object:

    > o.toString(); 
    "[object Object]" 

The toString() method will be called internally by JavaScript when an object is used in a string context. For example, alert() works only with strings, so if you call the alert() function passing an object, the toString()method will be called behind the scenes. These two lines produce the same result:

    > alert(o); 
    > alert(o.toString()); 

Another type of string context is the string concatenation. If you try to concatenate an object with a string, the object's toString() method is called first:

    > "An object: " + o; 
    "An object: [object Object]" 

The valueOf() method is another method that all objects provide. For the simple objects (whose constructor is Object()), the valueOf() method returns the object itself:

    > o.valueOf() === o; 
    true 

To summarize:

  • You can create objects either with var o = {}; (object literal notation, the preferred method) or with var o = new Object();
  • Any object, no matter how complex, inherits from the Object object and therefore, offers methods such as toString() and properties such as a constructor

Array

Array() is a built-in function that you can use as a constructor to create arrays:

    > var a = new Array(); 

This is equivalent to the array literal notation:

    > var a = []; 

No matter how the array is created, you can add elements to it as usual:

    > a[0] = 1; 
    > a[1] = 2; 
    > a; 
    [1, 2] 

When using the Array() constructor, you can also pass values that will be assigned to the new array's elements:

    > var a = new Array(1, 2, 3, 'four'), 
    > a; 
    [1, 2, 3, "four"] 

An exception to this is when you pass a single number to the constructor. In this case, the number is considered to be the length of the array:

    > var a2 = new Array(5); 
    > a2; 
     [undefined x 5] 

As arrays are created with a constructor, does this mean that arrays are in fact objects? Yes, and you can verify this using the typeof operator:

    > typeof [1, 2, 3]; 
    "object" 

As arrays are objects, this means that they inherit the properties and methods of the parent object:

    > var a = [1, 2, 3, 'four']; 
    > a.toString(); 
    "1,2,3,four" 
    > a.valueOf(); 
    [1, 2, 3, "four"] 
    > a.constructor; 
    function Array() { [native code] } 

Arrays are objects, but of a special type because:

  • The names of their properties are automatically assigned using numbers starting from 0.
  • They have a length property that contains the number of elements in the array.
  • They have more built-in methods in addition to those inherited from the parent object.

Let's examine the differences between an array and an object, starting by creating the empty array a and the empty object o:

    > var a = [], o = {}; 

Array objects have a length property automatically defined for them, while normal objects do not:

    > a.length; 
    0 
    > typeof o.length; 
    "undefined" 

It's ok to add both numeric and non-numeric properties to both arrays and objects:

    > a[0] = 1;  
    > o[0] = 1; 
    > a.prop = 2; 
    > o.prop = 2; 

The length property is always up to date with the number of numeric properties, while it ignores the non-numeric ones:

    > a.length; 
    1 

The length property can also be set by you. Setting it to a greater value than the current number of items in the array makes room for additional elements. If you try to access these non-existing elements, you'll get the value undefined:

    > a.length = 5; 
    5 
    > a; 
    [1, undefined x 4] 

Setting the length property to a lower value removes the trailing elements:

    > a.length = 2; 
    2 
    > a; 
    [1, undefined x 1] 

A few array methods

In addition to the methods inherited from the parent object, array objects also have specialized methods for working with arrays, such as sort(), join(), and slice(), among others (see Appendix C, Built-in Objects, for the complete list).

Let's take an array and experiment with some of these methods:

    > var a = [3, 5, 1, 7, 'test']; 

The push() method appends a new element to the end of the array. The pop() method removes the last element. The a.push('new') method works like a[a.length] = 'new', and a.pop() is like a.length-.

The push() method returns the length of the changed array, whereas pop() returns the removed element:

    > a.push('new'), 
    6 
    > a; 
    [3, 5, 1, 7, "test", "new"] 
    > a.pop(); 
    "new" 
    > a; 
    [3, 5, 1, 7, "test"] 

The sort() method sorts the array and returns it. In the next example, after sort, both a and b point to the same array:

    > var b = a.sort(); 
    > b; 
    [1, 3, 5, 7, "test"] 
    > a === b; 
    true 

The join() method returns a string containing the values of all the elements in the array glued together using the string parameter passed to join():

    > a.join(' is not '), 
    "1 is not 3 is not 5 is not 7 is not test" 

The slice() method returns a piece of the array without modifying the source array. The first parameter to slice() is the start index (zero-based), and the second is the end index (both indices are zero-based). Start index is included, while the end index is not. Take a look at the following example:

    > b = a.slice(1, 3); 
    [3, 5] 
    > b = a.slice(0, 1); 
    [1] 
    > b = a.slice(0, 2); 
    [1, 3] 

After all the slicing, the source array is still the same:

    > a; 
    [1, 3, 5, 7, "test"] 

The splice() method modifies the source array. It removes a slice, returns it, and optionally fills the gap with new elements. The first two parameters define the start index and length (number of elements) of the slice to be removed; the other parameters pass the new values:

    > b = a.splice(1, 2, 100, 101, 102); 
    [3, 5] 
    > a; 
    [1, 100, 101, 102, 7, "test"] 

Filling the gap with new elements is optional, so you can skip it:

    > a.splice(1, 3);  
    [100, 101, 102] 
    > a; 
    [1, 7, "test"] 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.172.249