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

MySQL table addition, deletion, modification and query basic tutorial

1. Create insert into [table name] (field1, field...

How to Install and Configure Postfix Mail Server on CentOS 8

Postfix is ​​a free and open source MTA (Mail Tra...

Detailed explanation of setting Context Path in Web application

URL: http://hostname.com/contextPath/servletPath/...

MySQL log settings and viewing methods

MySQL has the following logs: Error log: -log-err...

Solve the error during connect exception in Docker

When you first start using Docker, you will inevi...

Detailed explanation of CSS style cascading rules

CSS style rule syntax style is the basic unit of ...

JavaScript mobile H5 image generation solution explanation

Now there are many WeChat public account operatio...

5 common scenarios and examples of JavaScript destructuring assignment

Table of contents Preface 1. Extract data 2. Alia...

Web page creation for beginners: Learn to use HTML's hyperlink A tag

The hyperlink a tag represents a link point and i...

Eight rules for effective web forms

If you're collecting information from your us...

Example code for implementing an Upload component using Vue3

Table of contents General upload component develo...

How to extend Vue Router links in Vue 3

Preface The <router-link> tag is a great to...