Home Web Front-end JS Tutorial Explanation of typeof and object.prototype.toString to determine the type of various data in js_Basic knowledge

Explanation of typeof and object.prototype.toString to determine the type of various data in js_Basic knowledge

May 16, 2016 pm 05:17 PM
object typeof

1. typeof(param) returns the type of param (string)

This method is a global method defined in JS and is also the most commonly used method by compilers. The advantage is that it is simple to use and easy to remember. The disadvantage is that it cannot judge object, null, array, regexp and custom objects very well. .

Sample code:

Copy code The code is as follows:

var str='str' ;
var arr=['1','2'];
var num=1;
var bool=true;
var obj={name:'test'};
var nullObj=null;
var undefinedObj=undefined;
var reg=/reg/;

function fn(){
alert('this is a function');
}

function User(name){
this.name=name;
}
var user=new User('user');

console.log(typeof(str));
console.log(typeof(arr));
console.log(typeof(num));
console.log(typeof(bool) );
console.log(typeof(obj));
console.log(typeof(nullObj));
console.log(typeof(undefinedObj));
console.log(typeof( reg));
console.log(typeof(fn));
console.log(typeof(user));


The result is:
Copy code The code is as follows:

string
object
number
boolean
object
object
undefined
object
function
object

2. Object.prototype.toString().call(param) returns the type of param (string, format is [object class])

This method can support most types of judgment, and jquery encapsulated type judgment uses this method. Some people may seem a little confused, so let me break it down for you.

1) call(param) function

a.fun().call(b) means in js, let object b replace a, and then execute the fun function of a. Write an example:

Copy code The code is as follows:

function Class1()
{
this.name = "class1";

this.showNam = function()
{
alert(this.name);
}
}

function Class2()
{
this.name = "class2";
}

var c1 = new Class1();
var c2 = new Class2();

c1.showNam.call(c2);


The output is class2 instead of class1, which is equivalent to method inheritance.
So, Object.prototype.toString().call(param) actually means param.prototype.toString(), so why don’t we write param.prototype.toString() directly, but use call() Let’s take a detour, please see 2 below to understand.

2) Object.prototype.toString()

What is Object? , Script56.chm (the official M$ tutorial) says: Object provides functions common to all JScript objects. In fact, Object is the ancestor of all js objects. It is a concept. All objects in js are instances of Object, and then different objects Override your own independent method. As for prototype, you don’t need to go too deep. It just returns a reference to the prototype, and you can dynamically add methods and attributes to the prototype
A small example

Copy code The code is as follows:

function class(){
this.name = "class";
this.showName = function( ){
alert(this.name);
}
}
var obj = new class();
obj.showName();
class.prototype.showNameContact = function (){
alert("prototype test" this.name);
}
obj.showNameContact();

Then class and prototype test class will be output respectively. Originally, the showNameContact function is not defined in the constructor class(), but through prototype we can dynamically add functions to the object prototype, which will naturally be included in the new example. . So Object.prototype.toString() means to execute the toString method in the ancestor of Object.

So what does toString() do? The toString() function is defined in many js manuals like this: The
toString() method can convert a logical value into a string and return the result. The syntax is: booleanObject.toString(). As I said just now, objects in js are all inherited Objects. These objects have customized functions or reconstructed some functions of Object, and they all rewrite the toString() function. So we can't think of writing param.prototype.toString() directly in 1, so that the toString() function rewritten by param itself will be executed.

Okay, now comes the critical moment. What does toString() do and what is its role?

In ES3, the specification of the Object.prototype.toString method is as follows:

Object.prototype.toString()

When the toString method is called, the following steps will be performed:

1. Get the value of the [[Class]] attribute of this object.

2. Calculate the three strings "[object", the operation result Result(1) of the first step, and the new string after "]" concatenation.

3. Return the operation result of the second step Result(2).

In ES3, the specification document does not summarize how many types of [[class]] internal properties there are. However, we can count by ourselves. There are a total of 10 types of values ​​​​for the [[class]] internal properties of native objects. respectively. Is: "Array", "Boolean", "Date", "Error", "Function", "Math", "Number", "Object", "RegExp", "String". So Object.prototype.toString() The output result is a string in this format [object Array], [object Boolean].

In ES5.1, in addition to the specification being written in more detail, there are also some changes in the definition of the Object.prototype.toString method and [[class]] internal properties. The specification of the Object.prototype.toString method is as follows:

Object.prototype.toString ( )
When the toString method is called, the following steps will be performed:

1 If the value of this is undefined, return "[object Undefined]".
2 If the value of this is null, return "[object Null]".
3 Let O be The result of calling ToObject(this).
4 Let class become the value of O's internal property [[Class]].
5 Return the three strings "[object ", class, and "]" after concatenation New string.

It can be seen that there are 1, 2, and 3 more steps than ES3. Steps 1 and 2 are new rules and are quite special, because "Undefined" and "Null" do not belong to the values ​​of the [[class]] attribute. According to statistics, the types that can be returned are "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", "Number", "Object", "RegExp" ", "String" has two more types than ES3. The [[class]] of the arguments object has become "Arguments" instead of the previous "Object". There are also multiple global objects JSON, and its [[class ]]The value is "JSON".

Finally, I would like to remind everyone that the first letter of class in the [object class] returned by Object.prototype.toString().call(param) is capitalized, and even JSON is capitalized, so you can make judgments Convert them all to lowercase to prevent errors, just use Object.prototype.toString().call(param).toLowerCase().

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the methods of converting java Object to byte and byte to Object? What are the methods of converting java Object to byte and byte to Object? Apr 20, 2023 am 11:37 AM

Object to byte and byte to Object Today we will realize how to convert from Object to byte and how to convert from byte to Object. First, define a class student: packagecom.byteToObject;importjava.io.Serializable;publicclassstudentimplementsSerializable{privateintsid;privateStringname;publicintgetSid(){returnsid;}publicvoidsetSid(in

How to use methods in Java Object class How to use methods in Java Object class Apr 18, 2023 pm 06:13 PM

1. Introduction to the Object class Object is a class provided by Java by default. Except for the Object class, all classes in Java have inheritance relationships. By default, it will inherit the Object parent class. That is, objects of all classes can be received using the reference of Object. Example: Use Object to receive objects of all classes classPerson{}classStudent{}publicclassTest{publicstaticvoidmain(String[]args){function(newPerson());function(newStudent());}public

Java uses the getClass() function of the Object class to obtain the runtime class of the object Java uses the getClass() function of the Object class to obtain the runtime class of the object Jul 24, 2023 am 11:37 AM

Java uses the getClass() function of the Object class to obtain the runtime class of the object. In Java, each object has a class, which defines the properties and methods of the object. We can use the getClass() function to get the runtime class of an object. The getClass() function is a member function of the Object class, so all Java objects can call this function. This article will introduce how to use the getClass() function and give some code examples. use get

What is the relationship between basic data types and Object in java What is the relationship between basic data types and Object in java May 01, 2023 pm 04:04 PM

The relationship between basic data types and Object. I know everyone has heard that Object is the base class of all types, but this sentence is actually not correct, because the basic data types in Java have nothing to do with Object. Here are some examples For example, when calling the swap method, you cannot directly pass the int type to the swap(Objectobj) method, because Object actually has nothing to do with the basic data type. At this time, a finds that our types do not match, so it automatically wraps it. It has become an Integer type. At this time, it can be contacted with Object and the swap method can be successfully called. Object, a wrapper class of basic data types

PHP Notice: Trying to get property of non-object solution PHP Notice: Trying to get property of non-object solution Jun 24, 2023 pm 09:34 PM

PHPNotice: Tryingtogetpropertyofnon-object Solution When you are developing in PHP, you may encounter this error message: "Notice: Tryingtogetpropertyofnon-object." This error message is usually due to you using an uninitialized object, or It's because your object has lost its reference in a certain piece of code and cannot access the properties correctly.

How to define the Object structure of redis How to define the Object structure of redis May 28, 2023 pm 05:20 PM

Introduction to the two-tier data structure of Redis. One of the reasons for the high performance of redis is that each of its data structures is specially designed and supported by one or more data structures. These flexible data structures are relied upon to improve reading performance. Fetch and write performance. If you want to understand the data structure of redis, you can discuss it from two different levels: The first level is from the user's perspective. This level is also the calling interface that Redis exposes to the outside, such as: string, list, hash ,set,sortedset. The second level is from the perspective of internal implementation, which belongs to the lower level implementation, such as: dict, sds, ziplist, quicklist, skiplis

Solution to PHP Notice: Trying to get property of non-object Solution to PHP Notice: Trying to get property of non-object Jun 22, 2023 pm 02:43 PM

Solution to PHPNotice: Tryingtogetpropertyofnon-object In the process of writing code in PHP, we may encounter the error message "Tryingtogetpropertyofnon-object". This error message usually occurs because we are trying to access a non-existent object property, causing an error in the code. This error message usually appears in the following situations: The object does not exist

How to use Object class and System class in Java? How to use Object class and System class in Java? Apr 23, 2023 pm 11:28 PM

Object is the base class of all Java classes, the top of the entire class inheritance structure, and the most abstract class. Everyone uses toString(), equals(), hashCode(), wait(), notify(), getClass() and other methods every day. Maybe they don’t realize that they are methods of Object, and they don’t look at what other methods Object has. And think about why these methods should be placed in Object. 1. Introduction to JavaObject class - the super class of all classes Object is a special class in the Java class library and is also the parent class of all classes. In other words, Java allows any type of object to be assigned to the Object type

See all articles