You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在使用new Function方法时为函数参数设置默认值?

给new Function创建的函数参数设置默认值

你可以直接在new Function的参数定义中使用ES6的默认值语法,和定义普通函数的方式完全一致。

修改后的代码示例

let fileName = "fileone.js", args = [], options = {};
// 在参数列表中直接给somefunctionorValue指定默认值,比如设为null
let ls = new Function('fileName', 'args', 'options', 'somefunctionorValue = null', `....some...code...body...here`)
ls(fileName, args, options) // 不传第四个参数时,somefunctionorValue会自动使用默认值null

如果需要更复杂的默认值(比如函数、对象),也可以直接写在参数定义里:

let ls = new Function('fileName', 'args', 'options', 'somefunctionorValue = () => "default result"', `
  // 函数体内可以直接使用这个带默认值的参数
  console.log(somefunctionorValue());
`)
ls(fileName, args, options) // 会输出"default result"

本质上,new Function的参数列表就是在定义函数的形参,所以普通函数支持的形参语法(包括默认值、解构赋值等)在这里都能正常使用。

内容的提问来源于stack exchange,提问作者Gary

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 20:40:56