javascript - JavaScript 中的对象到字符串转换

标签 javascript

我正在研究 JavaScript 中的对象到字符串的转换。所有对象都继承两个转换函数 - toString()valueOf() 。当 JavaScript 尝试将对象转换为字符串时,它会搜索 toString()实现然后为 valueOf()执行。所以我覆盖了 toString()valueOf()这样:

var obj = {
x: 10,
y: 20,   
toString: function() {
    return "x = " + this.x + ", y = " + this.y;
},
valueOf: function() {
    return this.x + ", " + this.y;
}};

将对象文字与字符串连接起来:

console.log("hello " + obj);

输出:hello 10, 20

输出不应该是:hello x = 10, y = 20

感谢任何帮助。

最佳答案

console.log("hello "+ obj);中,对obj进行类型转换的运算符是+,称为加法运算符。

在加法运算符中,每个参数都被转换为没有类型提示的原始值,而不是转换为字符串。当将对象转换为没有类型提示的基元时,将使用 valueOf 方法(如果可用)。仅当 valueOf 不可调用或返回非原始值时,才会使用 toString。如果 valueOftoString 都返回非原始值,则会引发 TypeError

<小时/>

引用规范:

http://es5.github.com/#x11.6.1

11.6.1 The Addition operator ( + )

1) Let lref be the result of evaluating AdditiveExpression.
2) Let lval be GetValue(lref).
3) Let rref be the result of evaluating MultiplicativeExpression. 4) Let rval be GetValue(rref). 5) Let lprim be ToPrimitive(lval).
6) Let rprim be ToPrimitive(rval).
7) If Type(lprim) is String or Type(rprim) is String, then
...

NOTE 1 No hint is provided in the calls to ToPrimitive in steps 5 and 6.

http://es5.github.com/#x9.1

9.1 ToPrimitive

...

Object - Return a default value for the Object. The default value of an object is retrieved by calling the [[DefaultValue]] internal method of the object, passing the optional hint PreferredType. The behaviour of the [[DefaultValue]] internal method is defined by this specification for all native ECMAScript objects in 8.12.8.

http://es5.github.com/#x8.12.8

8.12.8 [[DefaultValue]] (hint)

When the [[DefaultValue]] internal method of O is called with no hint, then it behaves as if the hint were Number, unless O is a Date object (see 15.9.6), in which case it behaves as if the hint were String.

...

When the [[DefaultValue]] internal method of O is called with hint Number, the following steps are taken:

1) Let valueOf be the result of calling the [[Get]] internal method of object O with argument "valueOf".
2) If IsCallable(valueOf) is true then,

  • Let val be the result of calling the [[Call]] internal method of valueOf, with O as the this value and an empty argument list.
  • If val is a primitive value, return val.
    ...

关于javascript - JavaScript 中的对象到字符串转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15038908/

相关文章:

javascript - 服务 worker 发送的 CORS 预检请求,而不是常规请求

javascript - React Router Dom(四)以编程方式导航

javascript - 这被认为是一种稳定的排序方法吗?

javascript - jquery切换状态未将.text更改为以前的值

javascript - 首先或之前验证 Controller 逻辑

javascript - AJV - 如何在 Javascript 中添加自定义错误消息

javascript - 访问返回的 JSON 元素

javascript - 在javascript中获取节点的所有子节点

javascript - 鼠标悬停时jQuery透明图片描述幻灯片动画

javascript - 使用模板文字作为 id 从输入中获取数据