简体   繁体   English

为什么不能使用const关键字分配JavaScript对象的常量属性?

[英]Why is it impossible to assign constant properties of JavaScript objects using the const keyword?

First, I had asked is it possible: How to create Javascript constants as properties of objects using const keyword? 首先,我问是否有可能: 如何使用const关键字创建Javascript常量作为对象的属性?

Now, I gotta ask: why? 现在,我要问:为什么? The answer to me seems to be 'just because', but it would be so useful to do something like this: 对我来说,答案似乎是“仅仅因为”,但这样做是很有用的:

var App = {};  // want to be able to extend
const App.goldenRatio= 1.6180339887  // throws Exception

Why can constants set on an activation object work but not when set on they are set on any other? 为什么在激活对象上设置的常量可以工作,但在其他对象上设置的常量却不能工作?

What sort of damage can be done if this were possible? 如果可能的话,会造成什么样的损害?

What is the purpose of const , if not to prevent a public API from being altered? const的目的是什么(如果不防止更改公共API)?

If you want an unchangeable value in a modern browser, use defineProperty to create an unwritable (aka read-only) property: 如果要在现代浏览器中使用defineProperty更改的值,请使用defineProperty创建不可写(也称为只读)属性:

var App = {};
Object.defineProperty(App,'goldenRatio',{value:1.6180339887});
console.log( App.goldenRatio ); // 1.6180339887
App.goldenRatio = 42;
console.log( App.goldenRatio ); // 1.6180339887
delete App.goldenRatio;         // false
console.log( App.goldenRatio ); // 1.6180339887

If you don't pass writable:true in the options to defineProperty it defaults to false , and thus silently ignores any changes you attempt to the property. 如果未在defineProperty选项中传递writable:true ,则默认为false ,因此将无提示地忽略您对该属性所做的任何更改。 Further, if you don't pass configurable:true then it defaults to false and you may not delete the property. 此外,如果不传递configurable:true则默认为false并且您不能删除该属性。

除了const不受跨浏览器支持(这是ES6功能)外, const App.goldenRatio= 1.6180339887出于同样的原因var App.goldenRatio= 1.6180339887无效:您正在设置对象属性,因此在其前面加上varconst关键字是语法错误。

var MY_CONSTANT = "some-value"; var MY_CONSTANT =“某些值”; You can use conventions like ALL_CAPS to show that certain values should not be modified 您可以使用诸如ALL_CAPS之类的约定来表明某些值不应被修改

Going to answer the question you meant to ask and say never use const . 要回答您要问的问题并说永不使用const The interpreter doesn't do anything with it. 解释器对此不做任何事情。 All it does is mislead the developer into thinking s/he can assume that the value never changes, which is about as likely as if the const keyword weren't present. 它所做的所有事情都是在使开发人员误以为他/她可以假设值永远不会改变,这与const关键字不存在的可能性const

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM