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
),对此您无能为力.您得到的最佳解决方案可能是解构 arguments
const
初始化中的对象:
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 中使函数参数保持不变?


基础教程推荐
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01