Home > Web Front-end > JS Tutorial > body text

JavaScript determines the type of object

高洛峰
Release: 2016-11-28 11:43:44
Original
1239 people have browsed it

To summarize, there are four main ways to determine the type of an object: constructor attribute, typeof operator, instanceof operator and Object.prototype.toString() method.

constructor attribute

Constructor The predefined constructor attribute is the constructor itself.


var Foo = function(){};
Foo.prototype.constructor === Foo;//true The object generated by calling the constructor through new takes the prototype attribute of the constructor as the prototype. Although there is no concept of a class in JavaScript, the function of a constructor is similar to that of similar names, and it is an identifier of the object type. You can view the object's type by accessing the constructor property inherited by the object. Primitive type variables can also access the constructor property because JavaScript forms a wrapper object when accessed.


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 copied or overwritten, which will cause type judgment errors. Even though we generally don't intentionally assign a value to the constructor property, there are some cases where the value of the constructor property is different from what we expect. Look at 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 the prototype of the subclass is based on the instance of the parent class, accessing the constructor through the subclass instance is the parent class constructor. Therefore, in JavaScript object-oriented programming, we will add a code to correct the constructor attribute when defining the subclass.


derivedClass.prototype.constructor = derivedClass; Although it is convenient to use constructor to determine the variable type, it is not necessarily particularly safe, so you need to be careful.

cross-frame and cross-window issues:

If you determine the type of objects from different frames or variables from different windows, the constructor attribute does not work properly. Because the core types of different windows are different[1].

Use instanceof operator

instanceof operator to determine whether the prototype attribute of a certain constructor exists in the prototype chain of an object [2]. The concept of prototype chain can be read 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, Boolean types) except null and undefined. Instanceof does not work, but you can use the method of packaging objects to judge.


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 properly in cross-frame and cross-window situations.

Use the Object.prototype.toString() method

The Object.prototype.toString() method is a low-level method that returns a string that indicates the type of object. It can also be used to determine null and undefined. The 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]" often uses the slice method to intercept the results Medium type information:


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

It is already very detailed in an MDN document introduced this [3]. 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.1typeof The result of wrapping the object is 'object' requires attention. There is no evaluation of good or bad here (if you need to distinguish between packaged objects and primitive types). But typeof is not a robust method and should be used with caution. 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 labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!