Changing the object into a primitive value way

A general object into a primitive value

let a = {}

console.log(+a)  //NaN

console.log(`${a}`) //[object Object]

console.log(a + "") //[object Object]

When the object is converted to a basic type, priority call [Symbol.toPrimitive] Conversion

let a = {

  [Symbol.toPrimitive](type){

    if(type == 'number'){

      return 10

    }

    if(type == 'string'){

      return 'hello world'

    }

  }

}

console.log( + a) //10

console.log( `${ a }` )  //hello world

Guess you like

Origin www.cnblogs.com/vnwith/p/12580886.html