How to make function parameter constant in JavaScript?

后端 未结 8 1069
野的像风
野的像风 2020-12-13 12:43

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 n

8条回答
  •  温柔的废话
    2020-12-13 13:45

    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;
        …
    }
    

    Notice that this function will have a different arity (.length), if you need that you'll have to declare some placeholder parameters.

提交回复
热议问题