Reputation: 285
I understand there is a way to have the .constructor.name
be different from the variable the constructor is stored in
var Foo = function Bar() {};
console.log(new Foo().constructor.name) // => Bar
I was wondering if there is a hacky way to set an object's .constructor.name
to something that wouldn't be a valid JS function name, e.g. "Hello::World"
.
Setting it directly doesn't seem to work:
function Foo() {};
Foo.prototype.constructor.name = "Test"
console.log(new Foo().constructor.name) // => Foo
I've tried doing it with the Function
constructor, but is uses eval
, so the JS has to be valid despite being passed a string.
Upvotes: 1
Views: 165
Reputation: 92440
prototype.constructor.name
is defined as non-writable, which means you can't just change it with an assignment.
var Foo = function Bar() {};
console.log(Object.getOwnPropertyDescriptor(Foo.prototype.constructor, 'name'))
But, as you can see, it is configureable, which means you can redefine it. I have no idea if this is wise, but you can do it like:
var Foo = function Bar() {};
Object.defineProperty(Foo.prototype.constructor, 'name', {value: "Test"})
console.log(new Foo().constructor.name) // Test
Upvotes: 5