gpt4 book ai didi

javascript - toPrimitive 对于模板文字和字符串文字给出不同的结果

转载 作者:行者123 更新时间:2023-11-30 23:59:50 25 4
gpt4 key购买 nike

我想知道为什么在这种情况下模板字符串会产生[object Object]:

class Omg {}

const omg = new Omg()

Omg.prototype.valueOf = () => 6;

+omg
// 6
omg + ''
// "6"
'' + omg
// "6"
`${omg}`
// "[object Object]"

最佳答案

模板字符串显然使用 Object.toString() 来“翻译”其中的占位符 (${...})。模板字符串是奇妙的小野兽;)如果您希望在模板字符串中需要 valueOf标签函数 可能是一个好主意(请参阅代码片段和 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}`);

关于javascript - toPrimitive 对于模板文字和字符串文字给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60804857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com