Why is it impossible to assign constant properties

2019-07-17 07:21发布

问题:

First, I had asked is it possible: How to create Javascript constants as properties of objects using const keyword?

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?

回答1:

Going to answer the question you meant to ask and say never use 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.



回答2:

If you want an unchangeable value in a modern browser, use defineProperty to create an unwritable (aka read-only) property:

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. Further, if you don't pass configurable:true then it defaults to false and you may not delete the property.



回答3:

Apart from the fact that const is and not supported cross-browser (it's an ES6 feature), const App.goldenRatio= 1.6180339887 doesn't work for the same reason var App.goldenRatio= 1.6180339887 doesn't: you're setting an object property, so it's a syntax error to prepend it with a var or const keyword.



回答4:

var MY_CONSTANT = "some-value"; You can use conventions like ALL_CAPS to show that certain values should not be modified