Object. prototype. toString. call () method, object. tostring. call
Use the native toString () method on Object. prototype to determine the data type. Use the following method:
Object. prototype. toString. call (value)
1. determine the basic type:
Object.prototype.toString.call(null);//”[object Null]”Object.prototype.toString.call(undefined);//”[object Undefined]”Object.prototype.toString.call(“abc”);//”[object String]”Object.prototype.toString.call(123);//”[object Number]”Object.prototype.toString.call(true);//”[object Boolean]”
2. Determine the native reference type:
Function Type
Function fn(){console.log(“test”);}Object.prototype.toString.call(fn);//”[object Function]”
Date type
var date = new Date();Object.prototype.toString.call(date);//”[object Date]”
Array type
var arr = [1,2,3];Object.prototype.toString.call(arr);//”[object Array]”
Regular Expression
var reg = /[hbc]at/gi;Object.prototype.toString.call(arr);//”[object Array]”
Custom type
function Person(name, age) { this.name = name; this.age = age;}var person = new Person("Rose", 18);Object.prototype.toString.call(arr); //”[object Object]”
Obviously, this method cannot accurately determine whether a person is an instance of the Person class, but can only be judged using the instanceof operator, as shown below:
Console. log (person instanceof Person); // The output result is true.
3. Determine the native JSON object:
Var isNativeJSON = window. JSON & Object. prototype. toString. call (JSON); console. log (isNativeJSON); // The output result is "[object JSON]", indicating that JSON is native, otherwise it is not;
Note: Object. prototype. toString () itself is allowed to be modified, and we currently discuss the Object. prototype. the application of the toString () method assumes that the toString () method is not modified.