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

WBOY
WBOYOriginal
2016-05-16 17:17:051001browse

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:
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