Make toPrimitive转换取决于上下文 [英] Make toPrimitive conversion depend on the context

查看:42
本文介绍了Make toPrimitive转换取决于上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want an object to return one value in a numeric context and a completely different one in a string context. The following doesn't work.

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"


推荐答案

特别是对于连接运算符,没有办法强制将操作数视为字符串,语言要求将它们转换为原始值(即 .valueOf()

For the concatenation operator in particular there is no way to force the operands to be treated as strings, the language requires that they are converted to primitive values (i.e. .valueOf().

使用 String(foo)进行的唯一解决方案似乎是显式转换 foo.toString()

The only work arounds appear to be an explicit cast using String(foo) or foo.toString()

这篇关于Make toPrimitive转换取决于上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆