[英]toPrimitive gives different results for template literal and string literal
我想知道為什么在這種情況下模板字符串結果為[object Object]
:
class Omg {}
const omg = new Omg()
Omg.prototype.valueOf = () => 6;
+omg
// 6
omg + ''
// "6"
'' + omg
// "6"
`${omg}`
// "[object Object]"
模板字符串顯然使用Object.toString()
來“翻譯”其中的占位符 ( ${...}
)。 模板字符串是奇妙的小野獸 ;) 如果您最好在模板字符串中需要valueOf
, tag function
可能是一個想法(參見代碼段和MDN )
class Omg {} const omg = new Omg() Omg.prototype.valueOf = () => 6; console.log(+omg) console.log(omg + ''); console.log('' + omg); console.log(`${omg}`); // note: 7 to demo the tag function Omg.prototype.toString = () => 7; console.log(`${omg}`); // you can use a tag function to force use of valueOf function useValueOfWherePossible(strings, ...placeHolders) { let result = strings.raw[0]; for (const [i, phldr] of placeHolders.entries()) { result += (phldr.valueOf() || phldr) + strings.raw[i + 1]; } return result; } console.log(useValueOfWherePossible `${omg}`);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.