场景
当我写下以下代码时,我正在尝试一些 Javascript 对象编程(演示 here ):
var o = {
"key":1,
"value": 1234,
toString: function(){
var res = this.key + ";" + this.value;
return res;
}
};
var p = {
"key":2,
"value": 5678
};
document.write(o);
document.write("</br>");
document.write(p);
如您所见,使用 toString() 方法可以让 o 对象
显示而无需调用 toString() 方法,而 p 对象
显示为...作为什么?
问题
toString
文字是对象表示的一种默认名称吗?或者还有什么?[object Object]
符号是什么意思?
最佳答案
Is the toString literal a kind of default name for objects representation? Or what else?
它是对象的 toString
属性上的函数。
在 Javascript 中,当对象被转换为字符串时( EcmaScript §9.8: ToString ,例如在字符串连接中使用时,或者在 alert()
或 document.write()
)它的 toString
方法被调用(通过 ToPrimitive 和 DefaultValue - §8.12.8 )。
通常,您会在自定义对象的原型(prototype)上指定它,并且所有内置类型都有一个(例如Array.prototype.toString
,它用逗号连接值)。您已在对象文字中显式设置它。
What does the [object Object] notation mean?
这是对象的默认 toString
实现的结果,即。对于 Object
的所有实例。 EcmaScript §15.2.4.2指定 Object.prototype.toString
返回 [object
+class+]
,以及内部 [[class] ] 普通对象是“Object”。
关于Javascript 对象编程和对象表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12623681/