search
HomeWeb Front-endJS TutorialJavaScript determines the type of object

JavaScript determines the type of object

Nov 28, 2016 am 11:43 AM
javascript

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


Statement
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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software