JavaScript determines the object type

Source: Internet
Author: User

I have recently read some articles about how JavaScript judges object types. In conclusion, there are four methods to determine the Object type: constructor attribute, typeof operator, instanceof operator, and Object. prototype. toString () method.

Constructor attributes

The constructor attribute predefined by the constructor is the constructor itself.


Var Foo = function (){};
Foo. prototype. constructor = Foo; // true the object generated by calling the constructor through new is prototype of the constructor. Although JavaScript does not have the concept of a class, constructor functions similar names and identifies object types. The access object inherits the constructor attribute to view the object type. The original type of variables can also access the constructor attribute, because JavaScript forms a packaging object during access.


1 // basic objects
2 var obj = {name: "obj "};
3 obj. constructor === Object; // true
4
5 // self defined "class"
6 var Foo = function (){};
7 var f = new Foo ();
8 f. constructor === Foo; // true
9
10 // primitive types
11 // Number
12 var num = 1;
13 num. constructor === Number; // true
14 var nan = NaN;
15 nan. constructor === Number; // true
16 // Boolean
17 var B = true;
18 B. constructor === Boolean; // true
19 // String
20 var s = "string ";
21 s. constructor === String; // true
22 // Function
23 var Fun = function (){};
24 Fun. constructor ==== Function; // true; however, the constructor attribute can be re-copied or overwritten, which may cause type errors. Even though we generally do not assign values to the constructor attribute, in some cases, the value of the constructor attribute is different from the expected value. Take the following example:


Var baseClass = function (){};
Var derivedClass = function (){};
DerivedClass. prototype = new baseClass ();

Var obj = new derivedClass ();
Obj. constructor === derivedClass; // false;
Obj. constructor === baseClass; // true; Because prototype of the subclass is prototype of the parent class, accessing constructor through the subclass instance is the parent class constructor. Therefore, in JavaScript object-oriented programming, we add a code when defining a subclass to correct the constructor attribute.


DerivedClass. prototype. constructor = derivedClass; it is convenient to use constructor to determine the variable type, but it is not necessarily safe, so be careful.

Cross-frame and cross-window problems:

If you determine the type of the object from different frames or variables from different windows, the constructor attribute cannot work normally. Because the Core Types of different windows are different [1].

Use the instanceof Operator

The instanceof operator determines whether the prototype attribute of a constructor exists in the prototype chain of an object [2]. The concept of prototype chain can be viewed in JavaScript Object-Oriented Programming (1) prototype and inheritance. The following code forms the prototype chain obj1-> derivedClass. prototype-> baseClass. prototype->...-> Object. prototype. Object. prototype is the prototype of all objects. anyObj instanceof Object === true.


Var baseClass = function (){};
Var derivedClass = function (){};
DerivedClass. prototype = new baseClass (); // use inheritance

Var obj1 = new derivedClass ();
Obj1 instanceof baseClass; // true
Obj1 instanceof derivedClass; // true
Obj1 instanceof Object; // true

Obj2 = Object. create (derivedClass. prototype );
Obj2 instanceof baseClass; // true
Obj2 instanceof derivedClass; // true
Obj2 instanceof Object; // The trueconstructor attribute can be applied to primitive types (numbers, strings, and Boolean types) except null and undefined ). However, instanceof cannot be used, but you can use the method of packaging objects to determine.


3 instanceof Number // false
'Abc' instanceof String // false
True instanceof Boolean // false

New Number (3) instanceof Number // true
New String ('abc') instanceof String // true
New Boolean (true) instanceof Boolean // true however, instanceof does not work either in the case of cross-frame or cross-window.

Use the Object. prototype. toString () method

The Object. prototype. toString () method is an underlying method that returns a string that indicates the Object type. It can also be used to determine null and undefined. Most common types are listed below.


Object. prototype. toString. call (3); // "[object Number]"
Object. prototype. toString. call (NaN); // "[object Number]"
Object. prototype. toString. call ([1, 2, 3]); // "[object Array]"
Object. prototype. toString. call (true); // "[object Boolean]"
Object. prototype. toString. call ("abc"); // "[object String]"
Object. prototype. toString. call (/[a-z]/); // "[object RegExp]"
Object. prototype. toString. call (function () {}); // "[object Function]"

// Null and undefined in Chrome and Firefox. In IE "[object Object]"
Object. prototype. toString. call (null); // "[object Null]"
Object. prototype. toString. call (undefined); // "[object Undefined]"

// Self defined Objects
Var a = new Foo ();
Object. prototype. toString. call (a); // "[object Object]"

// Typed Wrappers
Var B = new Boolean (true );
Object. prototype. toString. call (B); // "[object Boolean]"
Var n = new Number (1 );
Object. prototype. toString. call (n); // "[object Number]"
Var s = new String ("abc ");
Object. prototype. toString. call (s); // "[object String]" The slice method is often used to capture the type information in the result:


Object. prototype. toString. call ("abc"). slice (8,-1); // "String" using the typeof Operator

This [3] is detailed in an MDN document. Typeof can return less information, including "undefined", "object", "boolean", "number", "string", "function", and "xml.

Type Result
Undefined "undefined"
Null "object"
Boolean "boolean"
Number "number"
String "string"
Host object (provided by the JS environment) Implementation-dependent
Function object (implements [[Call] in ECMA-262 terms) "function"
E4X XML object "xml"
E4X XMLList object "xml"
Any other object "object"


// Numbers
Typeof 37 = 'number ';
Typeof 3.14 = 'number ';
Typeof Math. LN2 === 'number ';
Typeof Infinity = 'number ';
Typeof NaN = 'number'; // Despite being "Not-A-number"
Typeof Number (1) = 'number'; // but never use this form!

// Strings
Typeof "" = 'string ';
Typeof "bla" = 'string ';
Typeof (typeof 1) ==='string'; // typeof always return a string
Typeof String ("abc") = 'string'; // but never use this form!

// Booleans
Typeof true = 'boolean ';
Typeof false = 'boolean ';
Typeof Boolean (true) = 'boolean'; // but never use this form!

// Undefined
Typeof undefined = 'undefined ';
Typeof blabla = 'undefined'; // an undefined variable

// Objects
Typeof {a: 1 }== 'object ';
Typeof [1, 2, 4] === 'object'; // use Array. isArray or object. prototype. toString. call to differentiate regular objects from arrays
Typeof new Date () = 'object ';

Typeof new Boolean (true) === 'object'; // this is confusing. Don't use!
Typeof new Number (1) === 'object'; // this is confusing. Don't use!
Typeof new String ("abc") === 'object'; // this is confusing. Don't use!

// Functions
Typeof function () {}== 'function ';
Typeof Math. sin = 'function ';


Typeof undefined; // "undefined"
Typeof null; // "object" This stands since the beginning of JavaScript
Typeof/s/= 'object'; // Conform to ECMAScript 5.1 typeof the packaging object results in 'object. It is not good or bad here (if you need to distinguish the packaging object from the original type ). However, typeof is not a robust method. Be careful when using it. For example:


Var s = "I am a string ";
Typeof s = "string ";
// Add a method to String
String. prototype. A_String_Method = function (){
Console. log (this. valueOf ());
Console. log (typeof this );
};
S. A_String_Method ();
// I am a string
// Object

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.