Detailed explanation of JavaScript object conversion to primitive value

Detailed explanation of JavaScript object conversion to primitive value

Object.prototype.valueOf()

The valueOf of an object is designed to return the primitive value of the object, and will automatically perform conversion of the object into its primitive value wherever it is needed. Click here for details.

Object.prototype.toString()

The toString() method returns a string representation of the object and is automatically performed where an object is expected to be converted to a string. The default toString() method of an object returns [object type], where type is the name of the object's constructor. Click here for details.

Symbol.toPrimitive

Symbol.toPrimitive(hint) method has the same function as valueOf(), but has a higher priority than valueOf(); and the method also accepts a parameter hint, which is used to indicate the specific type of the original value to be converted, which are as follows:

  • number: numeric type
  • string: string type
  • default: default
let obj = {
  [Symbol.toPrimitive](hint) {
    switch (hint) {
      case 'number':
        return 123;
      case 'string':
        return 'str';
      case 'default':
        return 'default';
      default:
        throw new Error();
     }
   }
};
2 * obj // 246
3 + obj // '3default'
obj == 'default' // true
String(obj) // 'str'

Object conversion primitive value

The above three methods are triggered when the object is expected to be converted into some primitive value.

1. Expected to be converted to string type

The corresponding hint type is string

Where output is performed, such as alert()

String(obj)

let a = {
  toString () {
    return '2'
  }
}
console.log(String(a)) // 2

String concatenation (+) operation

let a = {
  toString () {
    return '2'
  }
}
console.log(a + 'vv')

Template Strings

let a = {
  [Symbol.toPrimitive] (hint) {
    console.log(hint) // string
    return 2
  }
}
console.log(`Are you old ${a}?`) // Are you old 2?

2. Expected to be converted to a numeric type

The corresponding hint type is numbe

division:

let a = {
  valueOf () {
    return 2
  }
}
console.log(2 / a, a / 2) // 1 1

Number(obj):

let a = {
  [Symbol.toPrimitive] (hint) {
    console.log(hint) // number
    return 2
  }
}
console.log(Number(a)) // 2

Positive and negative signs (note that it is not an addition or subtraction operation):

let a = {
  [Symbol.toPrimitive] (hint) {
    console.log(hint) // number
    return 2
  }
}
console.log(+a) // 2
console.log(-a) // -2

3. Expected to be converted to the default type (other)

The corresponding hint type is default

Numeric addition (i.e. the object being added is a numeric type):

let a = {
  [Symbol.toPrimitive] (hint) {
    console.log(hint) // default
    return 2
  }
}
console.log(1 + a) // 3

This is a bit unexpected. I thought that the expected conversion type in this case should be a numeric type, but in fact it is default;

Boolean operations : all objects are converted to true;

let a = {
  [Symbol.toPrimitive] (hint) {
    console.log(hint) // No trigger return false
  }
}
console.log(Boolean(a), a && 123) // true 123

Boolean operations include ==

The order in which the three methods are triggered

First, determine whether the object has the Symbol.toPrimitive(hint) method. If so, execute the method. If not, execute the following steps.

If it is expected to be converted into a string type, the toString() method is executed first;

If it is expected to be converted to the default type or numeric type, the valueOf() method is executed first:

Note : If there is no valueOf() method, but a toString() method is defined, the toString() method will be executed;

Summarize

This article ends here. I hope it can be helpful to you. I also hope you can pay more attention to more content on 123WORDPRESS.COM!

You may also be interested in:
  • 4 common ways to create objects in js and their advantages and disadvantages
  • Introduction to JavaScript built-in objects
  • Introduction to JavaScript Object Immutability

<<:  Css3 realizes seamless scrolling and anti-shake

>>:  Solution to Mysql binlog log file being too large

Recommend

Difference between src and href attributes

There is a difference between src and href, and t...

Detailed description of common events and methods of html text

Event Description onactivate: Fired when the objec...

Design Reference Beautiful and Original Blog Design

All blogs listed below are original and uniquely ...

Javascript closure usage scenario principle detailed

Table of contents 1. Closure 2. Closure usage sce...

Linux system dual network card binding configuration implementation

System version [root@ ~]# cat /etc/redhat-release...

Some small methods commonly used in html pages

Add in the <Head> tag <meta http-equiv=&q...

Implementation of TCPWrappers access control in Centos

1. TCP Wrappers Overview TCP Wrappers "wraps...

jQuery canvas generates a poster with a QR code

This article shares the specific code for using j...

MySql8 WITH RECURSIVE recursive query parent-child collection method

background When developing a feature similar to c...

ElementUI implements sample code for drop-down options and multiple-select boxes

Table of contents Drop-down multiple-select box U...

How to use the Linux md5sum command

01. Command Overview md5sum - Calculate and verif...

Flex layout achieves fixed number of rows per line + adaptive layout

This article introduces the flex layout to achiev...

Nginx handles http request implementation process analysis

Nginx first decides which server{} block in the c...