如何使用 const 关键字创建 Javascript 常量作为对象的属性? [英] How to create Javascript constants as properties of objects using const keyword?

查看:37
本文介绍了如何使用 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

为什么通过引用传递的常量突然变成了变量?我知道 App 不会(或者更确切地说......不应该)是可变的;这只是一个观察...

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.

edit:感谢@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)中的相同语义通常被描述为按值调用,其中该值被暗示为对对象的引用.

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.

这篇关于如何使用 const 关键字创建 Javascript 常量作为对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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