JavaScript重命名函数(不是变量名)

问题描述 投票:0回答:1

我正在尝试更改由.toString()给出的函数的名称,或使用相同的主体创建具有新名称的新函数。

function func() {}
func.toString() // returns 'function func() {}'
changename(func, "newname") // this is the functionality that I am trying to achieve
func.toString() // should now return 'function newname() {}'

我尝试使用Object.defineProperty()来成功更新func.name而不是func.toString()返回的值。

Object.defineProperty(func, "name", {
  value: "newname",
  writable: true,
});
func.name // returns 'newname'
func.toString() // still returns 'function func() {}'

编辑:想要这样做的原因我需要采用一个具有未知名称的任意函数,并将其写入具有已知名称的文件中,例如(使用nodejs):

const fs = require("fs");
changename(func, "newname");
fs.writeFileSync("tmp.js", func.toString());

tmp.js然后包含:

function newname() {}
javascript function rename
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.