如何检查ES6的“变量"是否正确?是恒定的吗? [英] How to check that ES6 "variable" is constant?

查看:78
本文介绍了如何检查ES6的“变量"是否正确?是恒定的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道一些技巧吗?我尝试使用try-catch:

Does anyone know some tricks how to do it? I tried to use try-catch:

"use strict";

const a = 20;

var isConst = false;
try {
   var temp = a; a = a+1; a = temp;
} catch (e) {
   isConst = true;
}

但不幸的是,它仅在严格"模式下有效.如果没有严格使用",它会静默执行所有语句,而无需修改a.同样,我无法将此代码包装到一些方便的函数(例如isConstant(someConst))中,因为我将传递给该函数的任何参数将是一个新变量.有人知道如何创建isConstant()函数吗?

But unfortunately it works only in "strict" mode. Without "use strict" it perform all statements silently, without modification of a. Also I cannot wrap this code into some handy function (isConstant(someConst) for example) as any argument I'll pass to that function will be a new variable. So anyone know how to create isConstant() function?

推荐答案

我不认为有,但是我也不认为这是个大问题.我认为了解变量是否为const可能很有用,并且它在其他一些语言中也存在,但是实际上,由于您(或团队中的某人)将定义这些变量,因此您会知道变量的范围和类型.换句话说,不,你不能,但这也不是问题.

I don't think there is, but I also don't think this is a big issue. I think it might be useful to have the ability to know if a variable is const, and this exists in some other languages, but in reality since you (or someone on a team) will be defining these variables, you'd know the scope and the type of the variables. In other words, no you can't, but it's also not an issue.

唯一有用的情况是,您可以在运行时更改mutable属性,并且更改此属性具有实际的性能优势. letconstvar与编译器大致相同,唯一的区别是编译器会跟踪const,并会在编译之前检查分配.

The only case where it might be useful is if you could change the mutable property during runtime, and if changing this property had actual performance benefits; let, const, and var are treated roughly equally to the compiler, the only difference is that the compiler keeps track of const and will check assignments before it even compiles.

要注意的另一件事是,与let一样,const的作用域是当前作用域,因此,如果您有类似这样的内容:

Another thing to note is that just like let, const is scoped to the current scope, so if you have something like this:

'use strict';

const a = 12;

// another scope
{
  const a = 13;
}

有效.请注意,如果您未在新作用域中明确声明const a = 13,它将在更高的作用域中查找,并且会出现Read OnlyAssignment错误:

it's valid. Just be careful that it will look up in higher scopes if you don't explicitly state const a = 13 in that new scope, and it will give a Read Only or Assignment error:

'use strict';

const a = 12;

{
  a = 13; // will result in error
}

这篇关于如何检查ES6的“变量"是否正确?是恒定的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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