Object. prototype. toString. call () method, object. tostring. call

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.