是否可以使用闭包来模拟 Javascript 中的常量?

发布于 2024-07-14 21:10:08 字数 53 浏览 3 评论 0原文

是否可以使用闭包来模拟 Javascript 中的常量? 如果是这样,您能给我举个例子吗?

Is it possible to simulate constants in Javascript using closures? If so, can you please furnish me with an example?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

北凤男飞 2024-07-21 21:10:08

Firefox 和 Chrome 都支持 const 关键字。 IE 没有。 因此,如果您需要常量并且不需要支持 IE,const 是一个不错的选择。 但请记住,当将值分配给 const 时,这两种浏览器都不会产生运行时错误。 值只是保持不变。

否则,您必须使用函数来定义无法修改的常量:

function PI() { return 3.14159; }

var area = radius*radius * PI();

当然,您可以只编写从不修改某些变量的代码,并且可能为此类变量建立命名方案,以便您认识到它们永远不需要修改。 ..

// note to self: never assign values to variables utilizing all-uppercase name
var PI = 3.14159;

“模拟”常量的另一个选项是使用属性定义功能 在某些浏览器中可用于定义对象的只读属性。 当然,由于支持属性定义的浏览器不包括 IE,所以这并没有真正的帮助...(请注意,IE8 确实支持属性定义 以某种方式...但不是在 JavaScript 对象上)

最后,非常做作您可能会使用函数参数作为常量的场景(也许这就是您在建议闭包时所想到的?)。 虽然它们表现为变量,但它们的作用域仍然是定义它们的函数,因此不能影响修改它们的函数外部同名变量所持有的值:

var blah = 3;
var naw = "nope";
(function(blah, naw)
{
  blah = 2;
  naw = "yeah";
  alert(naw + blah); // "yeah2"
})(blah, naw);

alert(naw + blah); // "nope3"

请注意,与此类似的内容是 通常由 jQuery 插件使用,但原因相反:jQuery 代码通常使用 $ 简写来引用 jQuery 对象,但即使其他代码重新定义了该符号,该库仍将继续工作; 通过使用 $ 参数将库和插件代码包装在匿名函数中,然后传入 jQuery 作为参数,代码与其他库可能对值所做的更改隔离开来稍后$


另请参阅:Javascript 中有常量吗?

Firefox and Chrome both support the const keyword. IE does not. So if you need constants and don't need to support IE, const isn't a bad choice. Keep in mind though, neither browser produces a runtime error when a value is assigned to a const; the values merely remains unchanged.

Otherwise, you must use functions to define constants that cannot be modified:

function PI() { return 3.14159; }

var area = radius*radius * PI();

Of course, you could just write code that never modifies certain variables, and maybe establish a naming scheme for such variables such that you recognize that they will never need to be modified...

// note to self: never assign values to variables utilizing all-uppercase name
var PI = 3.14159;

Another option for "simulating" constants would be to use the property definition functionality available in some browsers to define read-only properties on an object. Of course, since the browsers supporting property definitions don't include IE, that doesn't really help... (note that IE8 does support property definitions after a fashion... but not on JavaScript objects)

Finally, in very contrived scenarios you might use function arguments as constants (perhaps this is what you were thinking of when you suggested closures?). While they behave as variables, they remain scoped to the function in which they are defined and cannot therefore affect the values held by variables with the same name outside of the function in which they are modified:

var blah = 3;
var naw = "nope";
(function(blah, naw)
{
  blah = 2;
  naw = "yeah";
  alert(naw + blah); // "yeah2"
})(blah, naw);

alert(naw + blah); // "nope3"

Note that something similar to this is commonly used by jQuery plugins, but for the opposite reason: jQuery code is usually written using the $ shorthand to refer to the jQuery object, but the library is intended to continue working even if some other code redefines that symbol; by wrapping library and plugin code in anonymous functions with a $ parameter and then passing in jQuery as an argument, the code is isolated from changes other libraries might make to the value of $ later on.


See also: Are there constants in Javascript?

回梦 2024-07-21 21:10:08

You can create read-only, named constants with the const keyword (Implemented in JavaScript 1.5).

红尘作伴 2024-07-21 21:10:08

据我所知:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript">
            function Scope()
            {
                return function()
                {
                    return {Constant: 1}; //Object literal
                };
            }
            var Scope = Scope();
        </script>
    </head>
    <body>
        <script type="text/javascript">
            document.write(Scope().Constant + "<br />");

            //The following line of code has no effect and fails silently.
            Scope().Constant = 6;

            document.write(Scope().Constant + "<br />");
        </script>
    </body>
</html>

这种方法允许我通过扩展对象文字来扩展范围以拥有多个常量成员变量。

This is as far as i got:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <script type="text/javascript">
            function Scope()
            {
                return function()
                {
                    return {Constant: 1}; //Object literal
                };
            }
            var Scope = Scope();
        </script>
    </head>
    <body>
        <script type="text/javascript">
            document.write(Scope().Constant + "<br />");

            //The following line of code has no effect and fails silently.
            Scope().Constant = 6;

            document.write(Scope().Constant + "<br />");
        </script>
    </body>
</html>

This approach allows me to extend the scope to have more than one constant member variable by extending the object literal.

小巷里的女流氓 2024-07-21 21:10:08

声明:

function globals(){
    const x1="something";
    const x2="otherthing";

    return{
      getX1=function(){
        return x1;
      },
      getX2=function(){
        return x2;
      }
    }
 }

var globalConstants=globals();

访问:

globalConstants.getX1();

To declare :

function globals(){
    const x1="something";
    const x2="otherthing";

    return{
      getX1=function(){
        return x1;
      },
      getX2=function(){
        return x2;
      }
    }
 }

var globalConstants=globals();

To access :

globalConstants.getX1();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文