改变对象转换为原始值的方式

一般一个对象转换为原始值

let a = {}

console.log(+a)  //NaN

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

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

对象转换为基本类型时,优先调用 [Symbol.toPrimitive]转换

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

posted @ 2020-03-27 13:43  小白白又白啦  阅读(134)  评论(0编辑  收藏  举报