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(); Is there away to make Object.prototype.toString.call(obj) return som
Solution 1:
ECMAScript5 doesn't provide any way to modify [[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 removed the [[Class]] internal slot, but you can use the @@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 method
Object.prototype.toString
.
Bar.prototype[Symbol.toStringTag] = 'Date';
Object.prototype.toString.call(newBar()); // "[object Date]"
Solution 2:
If you want data object - create it, then you can just extend it for your own purposes, but the overall idea 'smells'.
Bar.prototype.test = function () {
return'test';
};
functionBar(){
var resultObject = newDate();
Object.setPrototypeOf(resultObject, Object.assign(Object.create(Date.prototype), Bar.prototype));
return resultObject;
}
var obj = newBar();
obj.test() === 'test';
Object.prototype.toString.call(obj) === '[object Date]'
Post a Comment for "Is There Away To Change The Internal [[class]] Property Of A Javascript Object?"