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

Solution to elementui's el-popover style modification not taking effect

When using element-ui, there is a commonly used c...

MySQL 8.0.17 installation graphic tutorial

This article shares with you the MySQL 8.0.17 ins...

Steps to set up and mount shared folders on Windows host and Docker container

Programs in Docker containers often need to acces...

Solve the conflict between docker and vmware

1. Docker startup problem: Problem Solved: You ne...

Solution to the welcome to emergency mode message when booting CentOS7.4

Today I used a virtual machine to do an experimen...

Detailed explanation of MySQL multi-table join query

Table of contents Multi-table join query Inner Jo...

How to install and deploy ftp image server in linux

Refer to the tutorial on setting up FTP server in...

How to implement scheduled automatic backup of MySQL under CentOS7

The happiest thing that happens in a production e...

Implementation of Docker container connection and communication

Port mapping is not the only way to connect Docke...

Detailed steps for developing WeChat mini-programs using Typescript

We don't need to elaborate too much on the ad...

Introduction to Linux environment variables and process address space

Table of contents Linux environment variables and...

How to Enable or Disable Linux Services Using chkconfig and systemctl Commands

This is an important (and wonderful) topic for Li...

Vue simple implementation of turntable lottery

This article shares the specific code of Vue to s...

Understanding flex-grow, flex-shrink, flex-basis and nine-grid layout

1. flex-grow, flex-shrink, flex-basis properties ...

js implements a simple calculator

Use native js to implement a simple calculator (w...