指定 .constructor.name 为任意字符串

zlo*_*leo 1 javascript constructor function

我知道有一种方法可以使其.constructor.name与构造函数存储的变量不同

var Foo = function Bar() {};
console.log(new Foo().constructor.name) // => Bar
Run Code Online (Sandbox Code Playgroud)

我想知道是否有一种 hacky 方法可以将对象设置.constructor.name为不是有效 JS 函数名称的名称,例如"Hello::World".

直接设置好像不行:

function Foo() {};
Foo.prototype.constructor.name = "Test"
console.log(new Foo().constructor.name) // => Foo
Run Code Online (Sandbox Code Playgroud)

我尝试过使用Function构造函数来执行此操作,但它是使用eval,因此尽管传递了字符串,JS 也必须有效。

Mar*_*yer 5

prototype.constructor.name被定义为不可写,这意味着您不能仅通过赋值来更改它。

var Foo = function Bar() {};
console.log(Object.getOwnPropertyDescriptor(Foo.prototype.constructor, 'name'))
Run Code Online (Sandbox Code Playgroud)

但是,正如您所看到的,它是可配置的,这意味着您可以重新定义它。我不知道这是否明智,但你可以这样做:

var Foo = function Bar() {};

Object.defineProperty(Foo.prototype.constructor, 'name', {value: "Test"})
console.log(new Foo().constructor.name)  // Test
Run Code Online (Sandbox Code Playgroud)