如何在使用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
相关产品推荐
相关产品推荐

