假设我已经创建了一个函数构造函数,例如
function Bar(){
}
var obj = new Bar();
是否可以让 Object.prototype.toString.call(obj)
返回类似 [object Date]
的内容?
最佳答案
ECMAScript5不提供任何修改 [[Class]] 的方法:
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 Well-Known Symbol :
- 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 - 是否可以更改 JavaScript 对象的内部 [[Class]] 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35900557/