A brief talk on Tostirng () and Object.prototype.toString.call () methods in JavaScript

Source: Internet
Author: User
Tags hasownproperty

Brief discussion on TOSTIRNG () and Object.prototype.toString.call () method

What is the method of toString ()? It is a way to convert a value into a string. But how does it convert a value from one type to a string type?

With the following examples, we can get answers:

1. Convert the value of the Boolean type to a string type:

Console.log (True.tostring ());//"True" Console.log (False.tostring ());//"false"

2. Output the string type in its literal form:

var str = "test123y"; Console.log (Str.tostring ());//"test123y"

3. Convert the object type to a string type (JavaScript native array type, date type, regexp type, and number, Boolean, string, all of which are sub-types of object):

Custom object Type (no redefinition of ToString method):
var obj = {name: "Tom", Age:18};console.log (Obj.tostring ());//"[Object Object]" At this point the original toString () method that was inherited from object is called

The next three examples implement the ToString () method in a rewritten manner;

1.Array Type:

var arr = ["Tom", "Rose", 18];console.log (Arr.tostring ());//"tom,12,rose,18"

2.REGEXP type

var patten = new RegExp ("\\[hbc\\]at", "GI"), Console.log (Patten.tostring ());//"/\[hbc\]at/gi"

3.Date type

var date = new Date (2014,02,26);//Note the date of the creation of this format, whose month is March Console.log (date.tostring ());/"Wed Mar 00:00:00 gmt+0800" The output format is different from the browser, this is the output format of Firefox;

The 4.Number type also implements the ToString () method in an overridden manner, see the following example:

(1) It can accept an integer parameter and convert the number of calls to the method into the corresponding string:

var num = 16;console.log (num.tostring (2)),//10000 binary Console.log (num.tostring (8)),//20 octal Console.log (num.tostring ( 16));//10 Hex Console.log (num.tostring (5)),//31 Although there is no five-input, but such a parameter can be accepted by the toString () method

(2) Look at the following code:

Console.log (1.toString ());//This syntax error is incorrect, but the following wording is legal; Console.log ((1). ToString ());//"1" Console.log (typeof (1). ToString ());//stringconsole.log (1..toString ());//"1" Console.log (typeof (1). ToString ());//stringconsole.log (1.2. ToString ());//"1" Console.log (typeof (1). ToString ());//string
This is because the JavaScript engine interprets the code as "1.toString ()" for "." is a floating-point symbol, but because the characters after the decimal point are illegal, the syntax error is reported, and the following "1..toString () and 1.2.toStirng ()" notation, the JavaScript engine considers the first "." The decimal point, the two is the property access syntax, so all can be interpreted correctly, for "(1). TOSTIRNG ()" In the wording, with "()" to exclude "." interpreted as a grammatical interpretation of the decimal point, so this writing can be interpreted and executed;

(3) After the decimal point of the decimal fraction has a continuous 6 or more than 6 "0", the decimal will be output by means of e notation;

var num = 0.000006;//has 5 "0" Console.log (num.tostring ()) after the decimal point;//"0.000006" var num = 0.0000006;//6 "0" After the decimal point Console.log (Num.tostring ());//"6e-7"

(4) The number of digits in the integer portion of floating-point numbers is greater than 21 o'clock, and the output is represented by E;

var num = 1234567890123456789012;console.log (num.tostring ());//"1.2345678901234568e+21"

It is inevitable to see here that there are some questions, the values of these basic data types are constants, and constants are not methods, why can we call the method? The answer is this: The five basic types have a special reference type-the wrapper type-in addition to null and undefined. When the code is interpreted and executed, the underlying type is converted to a type, and the base type is converted to a reference type, so that the method that the reference type has access to can be called.

Where is the toString () method defined?

Run the following code:
var Pro = Object.prototype;var PR = pro.__proto__;//ie11 Previous version does not support this property Console.log (typeof Pro);//"Object" Console.log ( String (PRO);//"[Object Object]" Console.log (Pro.hasownproperty ("toString"));//trueconsole.log (typeof PR);//" Object "Console.log (String (PR));//" null "Console.log (Pr.hasownproperty (" toString ");//Error
So, toString () is defined on Object.prototype;

Third, use the native ToString () method on the Object.prototype to determine the data type, using 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 expressions
var reg =/[hbc]at/gi;object.prototype.tostring.call (arr);//"[Object Array]"
Custom Types
function person (name, age) {    this.name = name;    This.age = age;} var person = new Person ("Rose"); Object.prototype.toString.call (arr); "[Object Object]"
It is clear that this method does not accurately judge that a person is an instance of the person class, but can only be judged with the instanceof operator, as follows:
Console.log (person instanceof person);//Output is true

3. Determine the native JSON object:

var Isnativejson = window. JSON && Object.prototype.toString.call (JSON); Console.log (Isnativejson);//The output is "[Object JSON]" indicating that the JSON is native, otherwise not;

Note: the Object.prototype.toString () itself is allowed to be modified, and the application we are discussing now about the Object.prototype.toString () method assumes that the ToString () method has not been modified as a precondition.

A brief talk on Tostirng () and Object.prototype.toString.call () methods in JavaScript

Related Article

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.