Appendix C. Built-in Objects

This Appendix lists the built-in constructor functions outlined in the ECMAScript standard, together with the properties and methods of the objects created by these constructors.

Object

Object() is a constructor that creates objects, for example:

>>> var o = new Object();

This is the same as using the object literal:

>>> var o = {}; // recommended

You can pass anything to the constructor and it will try to guess what it is and use a more appropriate constructor. For example, passing a string to new Object() will be the same as using the new String() constructor. This is not a recommended practise, but still possible.

>>> var o = new Object('something'),
>>> o.constructor

String()

>>> var o = new Object(123);
>>> o.constructor

Number()

All other objects, built-in or custom, inherit from Object. So the properties and methods discussed below apply to all types of objects.

Members of the Object Constructor

Property/Method

Description

Object.prototype

The prototype of all objects (also an object itself). Anything you add to this prototype will be inherited by all other objects.

>>> var s = new String('noodles'),
>>> Object.prototype.custom = 1;

1

>>> s.custom

1

Members of the Objects Created by the Object Constructor

Property/Method

Description

constructor

Points back to Object

>>> Object.prototype.constructor === Object

true

>>> var o = new Object();
>>> o.constructor === Object

true

toString(radix)

Returns a string representation of the object. If the object happens be a Number object, then the radix parameter defines the base of the returned number. The default radix is 10.

>>> var o = {prop: 1};
>>> o.toString()

"[object Object]"

>>> var n = new Number(255);
>>> n.toString()

"255"

>>> n.toString(16)

"ff"

toLocaleString()

Same as toString() but matching the current locale. Meant to be implemented by objects such as Date() and provide locale-specific values, such as different date formatting.

valueOf()

Returns the this object itself, but for other types of objects may return a different value. For example, Number objects return a primitive number and Date objects return a timestamp.

>>> var o = {};
>>> typeof o.valueOf()

"object"

>>> var n = new Number(101);
>>> typeof n.valueOf()

"number"

>>> var d = new Date();
>>> typeof d.valueOf()

"number"

>>> d.valueOf()

1208158875493

hasOwnProperty(prop)

Returns true if a property is an own property of the object or false if it was inherited from the prototype chain. Also returns false if the property doesn't exist.

>>> var o = {prop: 1};
>>> o.hasOwnProperty('prop')

true

>>> o.hasOwnProperty('toString')

false

isPrototypeOf(obj)

Returns true if an object is used as a prototype of another object. Any object from the prototype chain can be tested, not only the direct ancestor.

>>> var s = new String(''),
>>> Object.prototype.isPrototypeOf(s)

true

>>> String.prototype.isPrototypeOf(s)

true

>>> Array.prototype.isPrototypeOf(s)

false

propertyIsEnumerable

(prop)

Returns true if a property shows up in a for-in loop.

>>> var a = [1,2,3];
>>> a.propertyIsEnumerable('length')

false

>>> a.propertyIsEnumerable(0)

tru e

Array

The Array constructor creates array objects:

>>> var a = new Array(1,2,3);

This is the same as the array literal:

>>> var a = [1,2,3]; //recommended

When you pass only one numeric value to the Array constructor, it's assumed to be the array length. An array with this length will be created, and filled with undefined elements.

>>> var a = new Array(3);
>>> a.length

3

>>> a

[undefined, undefined, undefined]

This can sometimes lead to some unexpected behavior. For example, the following use of the array literal is valid:

>>> var a = [3.14]
>>> a

[3.14]

However, passing the floating-point number to the Array constructor is an error:

>>> var a = new Array(3.14)

invalid array length

Members of the Array Objects

Property/Method

Description

length

The number of elements in the array.

>>> [1,2,3,4].length

4

concat(i1, i2, i3,...)

Merges arrays together.

>>> [1,2].concat([10,20], [300,400])

[1, 2, 10, 20, 300, 400]

join(separator)

Turns an array into a string. The separator parameter is a string and the default value is a comma.

>>> [1,2,3].join()

"1,2,3"

>>> [1,2,3].join('|')

"1|2|3"

>>> [1,2,3].join(' is less than ')

"1 is less than 2 is less than 3"

pop()

Removes the last element of the array and returns it.

>>> var a = ['une', 'deux', 'trois'];
>>> a.pop()

"trois"

>>> a

["une", "deux"]

push(i1, i2,i3,...)

Appends elements to the end of the array and returns the length of the modified array.

>>> var a = [];
>>> a.push('zig', 'zag', 'zebra','zoo'),

4

reverse()

Reverses the elements of the array and returns the modified array.

>>> var a = [1,2,3];
>>> a.reverse()

[3, 2, 1]

>>> a

[3, 2, 1]

shift()

Like pop() but removes the first element, not the last.

>>> var a = [1,2,3];
>>> a.shift();

1

>>> a

[2, 3]

slice

(start_index,

end_index)

Extracts a piece of the array without modifying the source array.

>>> var a = ['apple', 'banana','js', 'css', 'orange'];
>>> a.slice(2,4)

["js", "css"]

>>> a

["apple", "banana", "js", "css", "orange"]

sort(callback)

Sorts an array. Optionally accepts a callback function for custom sorting. The callback function receives two array elements as arguments and should return 0 if they are equal, 1 if the first is greater and -1 if the second is greater.

An example of a custom sorting function that does a proper numeric sort (since the default is character sorting):

function customSort(a, b){
  if (a > b) return 1; 
  if (a < b) return -1; 
  return 0;
}

Example use of sort():

>>> var a = [101, 99, 1, 5];
>>> a.sort();

[1, 101, 5, 99]

>>> a.sort(customSort);

[1, 5, 99, 101]

>>> [7,6,5,9].sort(customSort);

[5, 6, 7, 9]

splice(start, delete_count, i1, i2, i3,...)

This is probably the most powerful of the array functions. It can remove and add elements at the same time. The first parameter is where to start removing, the second is how many items to remove and the rest of the parameters are new elements to be inserted in the place of the removed ones.

>>> var a = ['apple', 'banana','js', 'css', 'orange'];
>>> a.splice(2, 2, 'pear', 'pineapple'),

["js", "css"]

>>> a

["apple", "banana", "pear", "pineapple", "orange"]

unshift(i1, i2, i3,...)

Like push() but adds the elements at the beginning of the array as opposed to the end. Like shift() but adds to the array as opposed to removing from it. Returns the length of the modified array.

>>> var a = [1,2,3]; 
>>> a.unshift('one', 'two'), 

5

>>> a 

["one", "two", 1, 2, 3]

Function

JavaScript functions are objects. They can be defined using the Function constructor, like so:

>>> var sum = new Function('a', 'b', 'return a + b;'),  

This is equivalent to the function literal:

>>> var sum = function(a, b){return a + b;};

or the more common:

>>> function sum(a, b){return a + b;}

The use of the Function constructor is discouraged in favor of the function literals.

Members of the Function Objects

Property/Method

Description

apply(this_obj, params_array)

Allows you to call another function while overwriting its this value. The first parameter that apply() accepts is the object to be bound to this inside the function and the second is an array of parameters to be passed to the function being called.

function whatIsIt(){
  return this.toString();
}
>>> var myObj = {};
>>> whatIsIt.apply(myObj);

"[object Object]"

>>> whatIsIt.apply(window);

"[object Window]"

call(this_obj, p1, p2, p3, ...)

Same as apply() but accepts parameters one by one, as opposed to as one array.

length

The number of parameters the function expects.

>>> alert.length

1

>>> parseInt.length

2

Boolean

The Boolean constructor creates boolean objects (not to be confused with boolean primitives). The boolean objects are not very useful and are listed here for the sake of completeness.

>>> var b = new Boolean();
>>> b.valueOf()

false

>>> b.toString()

"false"

A boolean object is not the same as a boolean primitive value. As you know, all objects are truthy:

>>> b === false

false

>>> typeof b

"object"

Boolean objects don't have any properties other than the ones inherited from Object.

Number

Creates number objects:

>>> var n = new Number(101);
>>> typeof n

"object"

>>> n.valueOf();

101

Number objects are not primitive objects, but if you use a number method on a primitive number, the primitive will be converted to a Number object behind the scenes and the code will work.

>>> var n = 123;
>>> typeof n;

"number"

>>> n.toString()

"123"

Members of the Number Constructor

Property/Method

Description

Number.MAX_VALUE

A constant property (cannot be changed) that contains the maximum allowed number.

>>> Number.MAX_VALUE

1.7976931348623157e+308

>>> Number.MAX_VALUE = 101;

Number.MAX_VALUE is read-only

Number.MIN_VALUE

The smallest number you can work with in JavaScript.

>>> Number.MIN_VALUE

5e-324

Number.NaN

Contains the Not A Number number.

>>> Number.NaN 

NaN

NaN is not equal to anything including itself.

>>> Number.NaN === NaN 

false

Number.NaN is more reliable than simply using NaN, because the latter can be overwritten by mistake.

>>> NaN = 1; // don't do this!

1

>>> NaN 

1

>>> Number.NaN 

NaN

Number.POSITIVE_INFINITY

Contains the Infinity number. This is more reliable than the global Infinity value (property of the global object) because it is read-only.

Number.NEGATIVE_INFINITY

Has the value -Infinity. See above.

Members of the Number Objects

Property/Method

Description

toFixed(fractionDigits)

Fixed-point representation of a number object as a string. Rounds the returned value.

>>> var n = new Number(Math.PI);
>>> n.valueOf();

3.141592653589793

>>> n.toFixed(3)

"3.142"

toExponential(fractionDigits)

Exponential notation of a number object as a string. Rounds the returned value.

>>> var n = new Number(56789);
>>> n.toExponential(2)

"5.68e+4"

toPrecision(precision)

String representation of a number object, either exponential or fixed-point, depending on the number object.

>>> var n = new Number(56789);
>>> n.toPrecision(2)

"5.7e+4"

>>> n.toPrecision(5)

"56789"

>>> n.toPrecision(4)

"5.679e+4"

>>> var n = new Number(Math.PI);
>>> n.toPrecision(4)

"3.142"

String

The String() constructor creates string objects. Primitive strings are turned into objects behind the scenes if you call a method on them as if they were objects.

Creating a string object and a string primitive:

>>> var s_obj = new String('something'), 
>>> var s_prim = 'something';
>>> typeof s_obj

"object"

>>> typeof s_prim

"string"

The object and the primitive are not equal when compared by type with ===:

>>> s_obj === s_prim

false

>>> s_obj == s_prim

true

length is a property of string objects:

>>> s_obj.length

9

If you access length on a non-object but a primitive string, the primitive is converted to an object behind the scenes and the operation is successful:

>>> "something".length

9

Members of the String Constructor

Property/Method

Description

String.fromCharCode (code1, code2, code3, ...)

Returns a string created using the input character codes:

>>> String.fromCharCode(115, 99, 114, 105, 112, 116);

"script"

Members of the String Objects

Property/Method

Description

length

The number of characters in the string.

>>> new String('four').length

4

charAt(pos)

Returns the character at the specified position. Positions start at 0.

>>> "script".charAt(0);

"s"

charCodeAt(pos)

Returns the code of the character at the specified position.

>>> "script".charCodeAt(0);

115

concat(str1, str2, ....)

Return a new string glued from the input pieces.

>>> "".concat('zig', '-', 'zag'),

"zig-zag"

indexOf(needle, start)

If the needle matches a part of the string, the position of the match is returned. The optional second parameter tells where the search should start from. Returns -1 if no match is found.

>>> "javascript".indexOf('scr')

4

>>> "javascript".indexOf('scr', 5)

-1

lastIndexOf(needle, start)

Same as indexOf() but starts the search from the end of the string. The last occurence of "a":

>>> "javascript".lastIndexOf('a') 

3

localeCompare(needle)

Compares two strings in the current locale. Returns 0 if the two strings are equal, 1 if the needle gets sorted before the string object, -1 otherwise.

>>> "script".localeCompare('crypt')

1

>>> "script".localeCompare('sscript')

-1

>>> "script".localeCompare('script')

0

match(regexp)

Accepts a regular expression object and returns an array of matches.

>>> "R2-D2 and C-3PO".match(/[0-9]/g)

["2", "2", "3"]

replace(needle, replacement)

Allows you to replace the matching results of a regexp pattern. The replacement can also be a callback function. Capturing patterns are available as $1, $2,...$9.

>>> "R2-D2".replace(/2/g, '-two')

"R-two-D-two"

>>> "R2-D2".replace(/(2)/g, '$1$1')

"R22-D22"

search(regexp)

Returns the position of the first regular expression match.

>>> "C-3PO".search(/[0-9]/)

2

slice(start, end)

Returns the part of a string identified by start and end position. If start is negative, then the start position is length + start, similarly if the end parameter is negative, the end position is length + end.

>>> "R2-D2 and C-3PO".slice(4,13)

"2 and C-3"

>>> "R2-D2 and C-3PO".slice(4,-1)

"2 and C-3P"

split(separator, limit)

Turns a string into an array. The second parameter, limit, is optional. The separator can also be a regular expression.

>>> "1,2,3,4".split(',')

["1", "2", "3", "4"]

>>> "1,2,3,4".split(',', 2)

["1", "2"]

substring(start, end)

Similar to slice(). When start or end are negative or invalid, they are considered 0. If they are greater than the string length, they are considered to be the length. If end > start, their values are swapped.

>>> "R2-D2 and C-3PO".substring(4, 13)

"2 and C-3"

>>> "R2-D2 and C-3PO".substring(13, 4)

"2 and C-3"

toLowerCase()

toLocaleLowerCase()

Transforms the string to lower case.

>>> "JAVA".toLowerCase()

"java"

toUpperCase()

toLocaleUpperCase()

Transforms the string to upper case.

>>> "script".toUpperCase()

"SCRIPT"

Date

The Date constructor can be used with several types of input:

  • You can pass values for year, month, date of the month, hour, minute, second and millisecond, like so:

    >>> new Date(2011, 0, 1, 13, 30, 35, 500)

    Sat Jan 01 2011 13:30:35 GMT-0800 (Pacific Standard Time)

  • You can skip any of the input parameters, in which case they are assumed to be 0. Note that month values are from 0 (January) to 11 (December), hours are from 0 to 23, minutes and seconds 0 to 59, and milliseconds 0 to 999.

  • You can pass a timestamp:

    >>> new Date(1293917435500)

    Sat Jan 01 2011 13:30:35 GMT-0800 (Pacific Standard Time)

  • If you don't pass anything, the current date/time is assumed:

    >>> new Date()

    Fri Apr 18 2008 01:13:00 GMT-0700 (Pacific Daylight Time)

  • If you pass a string, it's parsed in attempt to extract a possible date value:

    >>> new Date('May 4, 2008')

    Sun May 04 2008 00:00:00 GMT-0700 (Pacific Daylight Time)

Members of the Date Constructor

Property/Method

Description

Date.parse(string)

Similar to passing a string to new Date(), this method parses the input string in attempt to extract a valid date value. Returns a timestamp on success, NaN on failure:

>>> Date.parse('May 4, 2008')

1209884400000

>>> Date.parse('4th')

NaN

Date.UTC(year, month, date, hours, minutes, seconds, ms)

Returns a timestamp but in UTC (Coordinated Universal Time), not in local time.

>>> Date.UTC(2011, 0, 1, 13, 30, 35, 500)

1293888635500

Members of the Date Objects

Property/Method

Description/Example

toUTCString()

Same as toString() but in universal time. Here's how Pacific Standard (PST) local time differs from UTC:

>>> var d = new Date(2010, 0, 1);
>>> d.toString()

"Fri Jan 01 2010 00:00:00 GMT-0800 (Pacific Standard Time)"

>>> d.toUTCString()

"Fri, 01 Jan 2010 08:00:00 GMT"

toDateString()

Returns only the date portion of toString():

>>> new Date(2010, 0, 1).toDateString();

"Fri Jan 01 2010"

toTimeString()

Returns only the time portion of toString():

>>> new Date(2010, 0, 1).toTimeString();

"00:00:00 GMT-0800 (Pacific Standard Time)"

toLocaleString()

toLocaleDateString()

toLocaleTimeString()

Equivalent to toString(), toDateString(), and toTimeString() respectively, but in a friendlier format, according to the current user's locale.

>>> new Date(2010, 0, 1).toString();

"Fri Jan 01 2010 00:00:00 GMT-0800 (Pacific Standard Time)"

>>> new Date(2010, 0, 1).toLocaleString();

"Friday, January 01, 2010 12:00:00 AM"

getTime()setTime(time)

Get or set the time (using a timestamp) of a date object. The following example creates a date and moves it one day forward:

>>> var d = new Date(2010, 0, 1);
>>> d.getTime();

1262332800000

>>> d.setTime(d.getTime()+ 1000 * 60 * 60 * 24);

1262419200000

>>> d.toLocaleString()

"Saturday, January 02, 2010 12:00:00 AM"

getFullYear()

getUTCFullYear()

setFullYear(year, month, date)

setUTCFullYear(year, month, date)

Get/Set a full year using local or UTC time. There is also getYear() but it is not Y2K compliant, so getFullYear() should be used.

>>> var d = new Date(2010, 0, 1);
>>> d.getYear()

110

>>> d.getFullYear()

2010

>>> d.setFullYear(2011)

1293868800000

>>> d

Sat Jan 01 2011 00:00:00 GMT-0800 (Pacific Standard Time)

getMonth()

getUTCMonth()

setMonth(month, date)

setUTCMonth(month, date)

Get/Set month, starting from 0 (January):

>>> var d = new Date(2010, 0, 1);
>>> d.getMonth()

0

>>> d.setMonth(11)

1291190400000

>>> d.toLocaleDateString()

"Wednesday, December 01, 2010"

getDate()

getUTCDate()

setDate(date)

setUTCDate(date)

Get/Set date of the month.

>>> var d = new Date(2010, 0, 1);
>>> d.toLocaleDateString() 

"Friday, January 01, 2010"

>>> d.getDate();

1

>>> d.setDate(31);

1264924800000

>>> d.toLocaleDateString()

"Sunday, January 31, 2010"

getHours()

getUTCHours()

setHours(hour, min, sec, ms)

setUTCHours(hour, min, sec, ms)

getMinutes()

getUTCMinutes()

setMinutes(min, sec, ms)

setUTCMinutes(min, sec, ms)

getSeconds()

getUTCSeconds()

setSeconds(sec, ms)

setUTCSeconds(sec, ms)

getMilliseconds()

getUTCMilliseconds()

setMilliseconds(ms)

setUTCMilliseconds(ms)

Get/Set hour, minutes, seconds, milliseconds, all starting from 0.

>>> var d = new Date(2010, 0, 1);
>>> d.getHours() + ':' + d.getMinutes()

"0:0"

>>> d.setMinutes(59)

1262336399000

>>> d.getHours() + ':' + d.getMinutes()

"0:59"

getTimezoneOffset()

Returns the difference between local and universal (UTC) time, measured in minutes. For example the difference between PST (Pacific Standard Time) and UTC:

>>> new Date().getTimezoneOffset()

420

>>> 420/60

7

getDay()

getUTCDay()

Returns the day of the week, starting from 0 (Sunday):

>>> var d = new Date(2010, 0, 1); 
>>> d.toLocaleDateString() 

"Friday, January 01, 2010"

>>> d.getDay() 

5

>>> var d = new Date(2010, 0, 3); 
>>> d.toLocaleDateString() 

"Sunday, January 03, 2010"

>>> d.getDay() 

0

Math

Math is a little different from the other built-in objects, because it cannot be used as a constructor to create objects. It is just a collection of functions and constants. Some examples, to illustrate the difference, are given below:

>>> typeof String.prototype

"object"

>>> typeof Date.prototype

"object"

>>> typeof Math.prototype

"undefined"

>>> typeof Math

"object"

>>> typeof String

"function"

Members of the Math Object

Property/Method

Description

Math.E

Math.LN10

Math.LN2

Math.LOG2E

Math.LOG10E

Math.PI

Math.SQRT1_2

Math.SQRT2

These are some useful math constants, all read-only. Here are their values:

>>> Math.E

2.718281828459045

>>> Math.LN10

2.302585092994046

>>> Math.LN2

0.6931471805599453

>>> Math.LOG2E

1.4426950408889634

>>> Math.LOG10E

0.4342944819032518

>>> Math.PI

3.141592653589793

>>> Math.SQRT1_2

0.7071067811865476

>>> Math.SQRT2

1.4142135623730951

Math.acos(x)

Math.asin(x)

Math.atan(x)

Math.atan2(y, x)

Math.cos(x)

Math.sin(x)

Math.tan(x)

Trigonometric functions

Math.round(x)

Math.floor(x)

Math.ceil(x)

round() gives you the nearest integer, ceil() rounds up and floor() rounds down:

>>> Math.round(5.5)

6

>>> Math.floor(5.5)

5

>>> Math.ceil(5.1)

6

Math.max(num1, num2, num3, ...)

Math.min(num1, num2, num3, ...)

max() returns the largest and min() returns the smallest of the numbers passed to them as arguments. If at least one of the input parameters is NaN, the result is also NaN.

>>> Math.max(2, 101, 4.5)

101

>>> Math.min(2, 101, 4.5)

2

Math.abs(x)

Absolute value.

>>> Math.abs(-101)

101

>>> Math.abs(101)

101

Math.exp(x)

Exponential function: Math.E to the power of x

Math.log(x)

Natural logarithm of x.

Math.sqrt(x)

Square root of x .

>>> Math.sqrt(9)

3

>>> Math.sqrt(2) === Math.SQRT2

true

Math.pow(x, y)

x to the power of y.

>>> Math.pow(3, 2)

9

Math.random()

Random number between 0 and 1 (including 0).

>>> Math.random()

0.8279076443185321

RegExp

You can create a regular expression object by using the RegExp() constructor and passing the expression pattern as the first parameter and the pattern modifiers as the second.

>>> var re = new RegExp('[dn]o+dle', 'gmi'),

This matches "noodle", "doodle", "doooodle", and so on. It's equivalent to using the regular expression literal:

>>> var re = ('/[dn]o+dle/gmi'), // recommended

Chapter 4 and Appendix D contain more information on regular expressions and patterns.

Members of RegExp Objects

Property/Method

Description

global

Read-only. true if the g modifier was set when creating the regexp object.

ignoreCase

Read-only. true if the i modifier was set when creating the regexp object.

multiline

Read-only. true if the m modifier was set when creating the regexp object

lastIndex

Contains the position in the string where the next match should start. test() and exec() set this position after a successful match. Only relevant when the g (global) modifier was used.

>>> var re = /[dn]o+dle/g;
>>> re.lastIndex

0

>>> re.exec("noodle doodle");

["noodle"]

>>> re.lastIndex

6

>>> re.exec("noodle doodle");

["doodle"]

>>> re.lastIndex

13

>>> re.exec("noodle doodle");

null

>>> re.lastIndex

0

source

Read-only. Returns the regular expression pattern (without the modifiers).

>>> var re = /[nd]o+dle/gmi;
>>> re.source

"[nd]o+dle"

exec(string)

Matches the input string with the regular expression. On a successful match returns an array containing the match and any capturing groups. When the g modifier is used, it matches the first occurrence and sets the lastIndex property. Returns null when there's no match.

>>> var re = /([dn])(o+)dle/g;
>>> re.exec("noodle doodle");

["noodle", "n", "oo"]

>>> re.exec("noodle doodle");

["doodle", "d", "oo"]

test(string)

Same as exec() but only returns true or false.

>>> /noo/.test('Noodle')

false

>>> /noo/i.test('Noodle')

true

Error Objects

Error objects are created either by the environment (the browser) or by your code.

>>> var e = new Error('jaavcsritp is _not_ how you spell it'),
>>> typeof e

"object"

Other than the Error constructor, six additional ones exist and they all inherit Error:

  • EvalError

  • RangeError

  • ReferenceError

  • SyntaxError

  • TypeError

  • URIError

Members of the Error Objects

Property

Description

name

The name of the error constructor used to create the object:

>>> var e = new EvalError('Oops'),
>>> e.name

"EvalError"

message

Additional error information:

>>> var e = new Error('Oops... again'),
>>> e.message

"Oops... again"

..................Content has been hidden....................

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