如何使用const关键字创建Javascript常量作为对象的属性?
为什么不能将常量设置为变量本身的对象的属性?
How come constants cannot be set as properties of objects which are variables themselves?
const a = 'constant' // all is well
// set constant property of variable object
const window.b = 'constant' // throws Exception
// OR
var App = {}; // want to be able to extend
const App.goldenRatio= 1.6180339887 // throws Exception
为什么通过引用传递的常数突然变得可变?
编辑:我知道应用程序不会(或者更确切地说......)不可变;这只是观察......
And how come constants passed by reference suddenly become variable? I know App won't (or rather... SHOULDN'T) be mutable; this is just an observation...
(function() {
const App;
// bunch of code
window.com_namespace = App;
}());
window.com_namespace; // App
window.com_namespace = 'something else';
window.com_namespace; // 'something else'
一个组织良好,可扩展,面向对象的单一命名空间库怎么样?包含常数是否有这些限制?
How can a nicely organized, extensible, object-oriented, singly namespaced library containing constants be made with these limitations?
编辑:我相信zi42,但我只需要问为什么
I believe zi42, but I just have to ask why
你不能用常数来做。做一些行为与你想要的行为但不使用常量的唯一可行方法是定义一个不可写的属性:
You cannot do it with constants. The only possible way to do something that behaves like you want, but is not using constants, is to define a non-writable property:
var obj = {};
Object.defineProperty( obj, "MY_FAKE_CONSTANT", {
value: "MY_FAKE_CONSTANT_VALUE",
writable: false,
enumerable: true,
configurable: true
});
关于为什么 const
的问题传递给函数变得可变,答案是因为它是通过值而不是通过引用传递的。该函数获取一个与常量具有相同值的新变量。
Regarding your question as to why a const
passed to a function becomes variable, the answer is because it's passed by value and not by reference. The function is getting a new variable that has the same value as your constant.
编辑:感谢@pst注意到对象文字在javascript实际上并未通过引用传递,而是使用按分享呼叫:
edit: thanks to @pst for noting that objects literals in javascript are not actually "passed by reference", but using call-by-sharing:
虽然这个术语在Python社区中有广泛的用法,但其他语言(如Java和Visual Basic)中的相同语义通常被描述为call-by -value,其中值隐含为对象的引用。
Although this term has widespread usage in the Python community, identical semantics in other languages such as Java and Visual Basic are often described as call-by-value, where the value is implied to be a reference to the object.