Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
339 views
in Technique[技术] by (71.8m points)

ecmascript 6 - How to make function parameter constant in JavaScript?

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.

This won't work:

function constParam(const a){
    alert('You want me to '+a+'!');
}

Any ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...