How to make function parameter constant in JavaScript?(如何在 JavaScript 中使函数参数保持不变?)
问题描述
我想要做的是尽可能多地使用不可变变量,从而减少我的代码中移动部分的数量.我只想在必要时使用var"和let".
What I want to do is to use as many immutable variables as possible, thus reducing the number of moving parts in my code. I want to use "var" and "let" only when it's necessary.
这行不通:
function constParam(const a){
alert('You want me to '+a+'!');
}
有什么想法吗?
推荐答案
函数参数在 ES6 中将保持可变绑定(如 var),对此您无能为力.您得到的最佳解决方案可能是解构 argumentsconst 初始化中的对象:
Function parameters will stay mutable bindings (like var) in ES6, there's nothing you can do against that. Probably the best solution you get is to destructure the arguments object in a const initialisation:
function hasConstantParameters(const a, const b, const c, …) { // not possible
…
}
function hasConstantParameters() {
const [a, b, c, …] = arguments;
…
}
请注意,此函数将具有不同的元数 (.length),如果需要,您必须声明一些占位符参数.
Notice that this function will have a different arity (.length), if you need that you'll have to declare some placeholder parameters.
这篇关于如何在 JavaScript 中使函数参数保持不变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 JavaScript 中使函数参数保持不变?
基础教程推荐
- 如何添加到目前为止的天数? 2022-01-01
- fetch 是否支持原生多文件上传? 2022-01-01
- 原生拖动事件后如何获取 mouseup 事件? 2022-01-01
- npm start 错误与 create-react-app 2022-01-01
- 在 contenteditable 中精确拖放 2022-01-01
- Fabric JS绘制具有活动形状的多边形 2022-01-01
- Bootstrap 模态出现在背景下 2022-01-01
- 检查 HTML5 拖放文件类型 2022-01-01
- 即使用户允许,Gmail 也会隐藏外部电子邮件图片 2022-01-01
- Bokeh Div文本对齐 2022-01-01
