Javascript Object Oriented Design - Javascript Built-in Types

We can create and use custom objects with new Object().

Javascript has many other reference types.

The built-in types are:

ArrayAn ordered list of numerically indexed values
DateA date and time
ErrorA runtime error
FunctionA function type to represent all function instances
ObjectA generic object
RegExpA regular expression


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

var items = new Array(); 
var now = new Date(); 
var error = new Error("Error."); 
var func = new Function("console.log('Hi');"); 
var object = new Object(); 
var re = new RegExp("\\d+"); 
/*w w w  . jav a2*/
console.log(typeof items);
console.log(typeof now);
console.log(typeof error);
console.log(typeof func);
console.log(typeof object);
console.log(typeof re);

The code above generates the following result.

Literal Forms

The built-in reference types can also have literal forms.

Using literal can create a reference typed value without creating an object using the new operator and the object's constructor.

To create an object with object literal syntax, define the properties of a new object inside braces.

The following code shows how to create custom reference type.

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 : "JavaScript", 
    year : 2015,
    website: "" 

To use string literals as property names, which is useful to have spaces or other special characters:

var book = { 
    "name": "Java Script", 
    "year": 2015,
    "website": "" 

The objects created in the code above are logically equivalent to the following:

var book = new Object(); = "JavaScript"; 
book.year = 2015; = ""; 

We can define an array literal by enclosing comma-separated values inside square brackets.

For example:

var colors = [ "A", "B", "C" ]; 
console.log(colors[0]);     // "A" 

The code above generates the following result.

This code is equivalent to the following:

var colors = new Array("A", "B", "C") 
console.log(colors[0]);     // "A" 

The code above generates the following result.

Function Literals

We define functions using their literal form.

For example:

function myMethod(value) { 
   return value; 

// is the same as 

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

The code above defines the myMethod() function, which returns any value passed to it.

Regular Expression Literals

JavaScript has regular expression literals to define regular expressions without using the RegExp constructor.

Regular expression literals pattern is contained between two slashes, and any additional options are single characters following the second slash.

For example:

var numbers = /\d+/g; 
// is the same as 
var numbers = new RegExp("\\d+", "g"); 


The code above generates the following result.

When creating the pattern in as a string, we have to escape any backslashes.