2
<html>
   <head><title>Using the const Keyword</title>
       <script type="text/javascript">
          const NOON = 12;
          const FREEZING = 32; // Can't change
       </script>
   </head>
  <body bgcolor="silver">
    <big>
    <script type="text/javascript">
      document.write("Fahrenheit temp is " + FREEZING + ".<br />");
      FREEZING =32 + 10;
      NOON = NOON + " noon";
      document.write("Make it warmer " + FREEZING + ".<br />");
      document.write("See you at ", NOON, ".<br />");
    </script>
  </big>
 </body>
</html>

以上代码在 Firefox、Chrome、Safari 上运行良好,但不适用于 Opera 12.02。由于我使用了关键字 'const' 结果应该如下

华氏温度是 32。让它变暖 32。12 点见。

但是Opera浏览器显示

华氏温度是 32。让它变暖 42。中午 12 点见。

这里有什么问题。

4

4 回答 4

3

从这里

const 的当前实现是 Mozilla 特定的扩展,不是 ECMAScript 5 的一部分。它在 Firefox 和 Chrome (V8) 中受支持。从 Safari 5.1.7 和 Opera 12.00 开始,如果您在这些浏览器中使用 const 定义变量,您以后仍然可以更改其值。Internet Explorer 6-9 或 Internet Explorer 10 的预览版不支持它。 const 关键字当前在函数范围内声明常量(如用 var 声明的变量)。

于 2012-09-22T15:28:55.550 回答
2

问题是constOpera 没有正式支持,仅此而已。开发人员声称这一点已经很长时间了,但它仍然落后。它仍然不是 ECMASCript 的一部分。

试试这个:

Object.defineProperty(window, "NOON", {
    value: 12, writable: false, configurable: false
});

这适用于 Opera。如果你也打算支持 IE<9,你应该使用一些不同的东西(而且效率较低):

Object.defineProperty(window, "NOON", {
    get: function() {return 12;}
});

您仍然无法更改其值,但您可以使用 重新NOON定义Object.defineProperty

于 2012-09-22T15:29:56.397 回答
1

const不是标准的 JavaScript 关键字。并非所有浏览器都有它。改用var

var FREEZING = 32;
于 2012-09-22T15:29:40.033 回答
0

最后浏览器支持它现在(2017)完美-> https://caniuse.com/#feat=const

于 2017-07-19T11:30:24.800 回答