Javascript Object Oriented Design - Javascript Identify reference Types








To identify the primitive types we used the typeof operator.

typeof operator on a function return "function":


function reflect(value) { 
    return value; 
} 

console.log(typeof reflect);    // "function" 

Example

The following code shows that applying typeof operator on reference type variabls return object.


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+"); 
//from  www  .j  a  v a  2  s.  c o m
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.

This is not very useful as we sometime would like to know the type an object is representing.





instanceof

To identify reference types, we 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 = {}; 
//  w w  w  .ja  va  2 s  . com
function reflect(value) { 
   return value; 
} 

console.log(items instanceof Array);        // true 
console.log(object instanceof Object);      // true 
console.log(reflect instanceof Function);   // true 

The code above generates the following result.

The instanceof operator can identify inherited types.

Every object is an instance of Object because every reference type inherits from Object.

The following code examines the three references created with instanceof:


var items = []; 
var object = {}; 
//  ww w.j  ava  2s.c  o  m
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 

The code above generates the following result.





Identifying arrays

Array.isArray() identifies the value as an instance of Array.

This method returns true when it receives a value that is a native array.


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

The code above generates the following result.