One day practice-js the relationship and difference between toString and valueof methods

Source: Internet
Author: User

The relationship between ToString and valueof in type conversion and its difference analysis

The first is to see how ES5 's specifications are explained.

Here are a few basic knowledge points to look at:

    1. [[class]]
      [[class]] is an intrinsic property of object, and the type of the value is returned as a String , which acts as A string value that describes the classification of objects defined by the specification. Each built-in object of the
      ES5 specification defines a [[Class]] intrinsic property value. The value of the [[Class]] intrinsic property of the host object can be in addition to "Arguments", "Array", "Boolean", "Date", "Error", "Function", "JSON", "Math", " Any string of number "," Object "," RegExp "," string ". The value of the internal property of the [[Class]] is used to distinguish the kind of objects within. Note that this specification does not provide any means for the program to access this value except through Object.prototype.toString .

      From ES5 type

    2. [[Primitivevalue]]
      [[Primitiveva Lue]] is an internal property that is defined only in certain objects and whose value is of the original type, and is associated with the internal state information of this object. The standard built-in object can only be implemented with Boolean, Date, number, String object [[Primitivevalue] .

      From ES5 type

    3. toobject
      toobject abstract operation based on The table converts its arguments to the value of the object type:

input type Results
Not defined Throws a TypeError exception.
Null value Throws a TypeError exception.
Boolean value Creates a new Boolean object whose [[PrimitiveValue]] properties are set to the value of the parameter.
Numerical Creates a new number object whose [[PrimitiveValue]] properties are set to the value of the parameter.
String Creates a new string object whose [[PrimitiveValue]] properties are set to the value of the parameter.
Object The result is the input parameter (not converted)

Excerpt from ES5 type conversion and testing

Object.prototype.toString ()

When calling toString a method, take the following steps:

    1. If this the value is undefined , return [object Undefined].
    2. If this the value is null , return [object Null].
    3. Make o the result of the this call as a parameter ToObject .
    4. The class value of the [[Class]] internal property that is made to O.
    5. Returns a string of three strings, "[Object", class and "]" connected together.

      Excerpt from ES5 Object.prototype.toString ()

Object.prototype.valueOf ()

When calling valueOf a method, take the following steps:

    1. Make o the result of the this call as a parameter ToObject .
    2. If O is the result of invoking the constructor with the host object 15.2.2.1 as a parameter Object , the
      2.1. Return o or return the original host object that was previously passed to the constructor. The specific results returned are defined by the implementation.
    3. Returns O.

      Excerpt from ES5 Object.prototype.valueOf ()

ToString () and valueof ()

All of the objects inherit two conversion methods.

  1. toString()
    The function is to return a string that reflects the object. The default toString() method return value
    js ({x:1, y:2}).toString() // => "[object Object]"
    1.1. Array classes (Arrays Class)
    Converts each array element to a string and merges the result string after adding a comma between the elements.

      [1,2,3].toString// => "1,2,3"

    1.2. Functions classes (function Class)
    Returns the representation of the implementation definition of this function. In fact, this is usually accomplished by converting a user-defined function to a JavaScript source code string.

      (function{f}).toString()  // => "function(x) {\n f(x) \n }"

    1.3. Date Class
    Returns a readable (meaning a method that can be passed through JavaScript and then encapsulated) date and time strings.

    newDate().toString// => "Tue Apr 24 2018 09:43:31 GMT+0800 (中国标准时间)"

    1.4. REGEXP classes (REGEXP Class)
    Converts a RegExp object to a string that represents the direct amount of a regular expression.

    /\d+/g.toString// => "/\\d+/g"
  2. ValueOf ()
    The task of this method is not defined in detail: if there is any original value, it will by default convert the object to the original value that represents it. Objects are composite values, and most objects cannot really be represented as an original value, so the default valueOf() method simply returns the object itself instead of returning a raw value.
    2.1. Arrays, functions, and regular expressions simply inherit this default method, and methods that invoke instances of these types simply valueOf() return the object itself.
    2.2. The method defined by the date class valueOf() returns the amount of an internal representation: the number of milliseconds since January 1, 1970.
    js var d = new Date(2018,4,1) // => 2018年5月1日 d.valueOf() // => 1525104000000

    Refer to the 3.8 type conversions in type, value, and variables in chapter 3rd of the JavaScript Authoritative Guide (6th edition) (Chinese version)

object is converted to the original value
    1. To convert an object to a Boolean value:
      All objects, including numeric values and functions, are converted to true . This is also true for wrapper functions: new Boolean(false) An object instead of the original value, which is converted totrue
    2. Object-to-string conversions:
      2.1. Call this method if the object has a toString() method. If it returns a primitive value, JavaScript converts the original value to a string (if it is not a string itself) and returns the result of the string.
      2.2. If the object has no toString() methods, or if the method does not return a primitive value, then JavaScript calls the valueOf() method. If this method is present, JavaScript calls it. If the return value is the original value, JavaScript converts the value to a string (if it is not a string itself) and returns the result of the string.
      2.3. Otherwise, JavaScript will not be able to toString() valueOf() get a raw value from or, so it throws a type error exception.
    3. Object-to-number conversions:
      3.1. If the object has valueOf() a method and the latter returns a primitive value, JavaScript converts the original value to a number (if necessary) and returns the number.
      3.2. Otherwise, if the object has toString() a method and the latter returns a raw value, JavaScript converts and returns it. The object's toString() method returns a string literal (the original value here), and JavaScript converts the string to a numeric type and returns the number.
      3.3. Otherwise, JavaScript throws a type error exception.

      Refer to the 3.8 type conversions in type, value, and variables in chapter 3rd of the JavaScript Authoritative Guide (6th edition) (Chinese version)

Example explanation
  1. An empty array is converted to the number 0, and an array with a single element is also converted to an array.

    Number// => 0Number([‘1234‘// => 1234

    The array inherits the default valueOf() method, which returns an object instead of an original value, so the array-to-number conversion invokes the toString() method. An empty array is converted to an empty string, and an empty string is converted to a number 0.

    // [] => ‘‘ => 0[].valueOf// => [][].toString// => ‘‘‘‘// => 0

    The result of converting an array of elements into a string is the same as the result of converting the string to this element. If the array contains only one numeric element, the number is converted to a string, and then the number is converted.

    [1].valueOf// => [1][1].toString// => "1""1"// => 1
  2. +Operators can perform numeric addition and string join operations.
    If one of its operands is an object, JavaScript uses a special method to convert the object to the original value instead of performing the object-to-method conversion.
    This special way means that valueOf() toString() the original value passed or returned will be used directly without being coerced into a number or string.
    +, == ,, != and relational operators also do the conversion of an object to the original value, but to remove the special case of a Date object: Any object will first attempt to call valueof () and then call ToString (). Regardless of whether the resulting raw value is used directly, it is not further converted to a number or string.

    Refer to the 3.8 type conversions in type, value, and variables in chapter 3rd of the JavaScript Authoritative Guide (6th edition) (Chinese version)

One day practice-js the relationship and difference between toString and valueof methods

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.