Make toPrimitive转换取决于上下文

geo*_*org 8 javascript types

我希望一个对象在数字上下文中返回一个值,在字符串上下文中返回一个完全不同的值.以下不起作用.

foo = {
    toString: function() { return "string" },
    valueOf:  function() { return 123 }
}

console.log(foo * 2)       // got 246, fine
console.log("hi " + foo)   // got "hi 123", want "hi string"
Run Code Online (Sandbox Code Playgroud)

Aln*_*tak 3

加法运算符将使用内部抽象操作将两个操作数转换为基元ToPrimitive,然后,如果一个操作数是字符串,它将使用内部抽象操作将ToString两个操作数都转换为字符串(注意:这与用户态对象上的方法不同toString。 )

结果是,通过添加Symbol.toPrimitive语言,您现在可以实现您的目标:

const foo = {
  [Symbol.toPrimitive](hint) {
    switch (hint) {
      case "string":
      case "default":
        return "string"
      case "number":
        return 123
      default:
        throw "invalid hint"
    }
  }
}

console.log(foo * 2) // 246
console.log("hi " + foo) // "hi string"
Run Code Online (Sandbox Code Playgroud)