如何使JavaScript中的函数参数不变? [英] How to make function parameter constant in JavaScript?

查看:93
本文介绍了如何使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 ),您无法做到这一点。您可能获得的最佳解决方案是将 参数对象 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;
    …
}

请注意,此函数将具有不同的 code> .length ),如果需要,您必须声明一些占位符参数。

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

这篇关于如何使JavaScript中的函数参数不变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆