有没有改变JavaScript对象的内部[[Class]]属性? [英] Is there away to change the internal [[Class]] property of a JavaScript Object?
问题描述
假设我已经创建了一个函数构造函数,例如
Suppose that I have created a function constructor such as
function Bar(){
}
var obj = new Bar();
是否需要制作 Object.prototype.toString.call(obj)
返回类似 [object Date]
?
Is there away to make Object.prototype.toString.call(obj)
return something like [object Date]
?
推荐答案
ECMAScript5 不提供任何方式修改[[Class]]:
ECMAScript5 doesn't provide any way to modify [[Class]]:
此规范不定义ECMAScript语言运算符或允许程序的
内置函数修改对象的
[[Class]]或[[Prototype]]内部属性或将[[Extensible]]的值
从false更改为true。修改[[Class]],[[Prototype]]或[[Extensible]]的实现特定
扩展必须
不违反前一段中定义的不变量。
This specification defines no ECMAScript language operators or built-in functions that permit a program to modify an object’s [[Class]] or [[Prototype]] internal properties or to change the value of [[Extensible]] from false to true. Implementation specific extensions that modify [[Class]], [[Prototype]] or [[Extensible]] must not violate the invariants defined in the preceding paragraph.
ECMAScript6删除了[[Class]]内部插槽,但你可以使用@@ toStringTag 众所周知的符号:
ECMAScript6 removed the [[Class]] internal slot, but you can use the @@toStringTag Well-Known Symbol:
- 规格名称
@@ toStringTag
- [[描述]]
Symbol.toStringTag
- 值和目的
一个字符串值属性,用于创建默认字符串描述宾语。通过内置方法访问Object.prototype.toString
。
- Specification Name
@@toStringTag- [[Description]]
"Symbol.toStringTag"
- Value and Purpose
A String valued property that is used in the creation of the default string description of an object. Accessed by the built-in methodObject.prototype.toString
.
Bar.prototype[Symbol.toStringTag] = 'Date';
Object.prototype.toString.call(new Bar()); // "[object Date]"
这篇关于有没有改变JavaScript对象的内部[[Class]]属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!