How to make function parameter constant in JavaScript?

后端 未结 8 1026
野的像风
野的像风 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:37

    There is no way to force a parameter to be immutable in JavaScript. You have to keep track of that yourself.

    Just write in a style where you happen not to mutate variables. The fact that the language doesn't provide any facilities to force you to do so doesn't mean that you can't still do it anyway.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题