Javascript 简明教程

JavaScript - Strict Mode

Strict Mode in JavaScript

在 JavaScript 中, strict mode 在 ES5(ECMAScript 2009)中引入。引入“严格模式”的目的是让 JavaScript 代码更安全。

In JavaScript, the strict mode is introduced in the ES5 (ECMAScript 2009). The purpose behind introducing the "strict mode" is to make the JavaScript code more secure.

“@ {s0}” 是 JavaScript 代码中用来添加严格模式的语法常量。它可以从代码中移除静默错误,例如,在未声明变量的情况下就使用变量,无法修改对象的只读属性等。

The 'use strict' literal expression is used to add the strict mode in the JavaScript code. It removes the silent errors from the code, such as you can’t use the variable without declaration, you can’t modify the readable property of the object, etc.

Enabling Strict Mode

要启用严格模式,应在代码顶部写入以下语法常量:

To enble strcit mode, you should write the following literal expression to the top of your code −

'use strict';

“use strict” 指令用于启用 JavaScript 的严格模式。

The 'use strict' directive is used enable JavaScript’s strict mode.

Why Use the Strict Mode?

以下是使用 JavaScript 严格模式的几点原因:

Here, we have listed some reasons for using the strict JavaScript mode −

  1. Error Prevention − The strict mode prevents the common errors which developers make while writing the JavaScript code, such as initializing the variable without declaration or using the reserved keywords as an identifier.

  2. Safer Code − The strict mode prevents the creation of global variables accidentally. Also, it doesn’t allow to use of statements like 'with', which can lead to vulnerability in the code.

  3. Future Compatibility − You can align your code with the future versions of JavaScript by using the script mode. For example, the current version of JavaScript doesn’t contain keywords like 'public' but is reserved for future versions. So, the strict mode won’t allow you to use it as an identifier from now.

Strict Mode in the Global Scope

在 JavaScript 代码顶部添加 “@ {s4}” 时;它对整个代码都使用了严格模式。

When you add the 'use strict' at the top of the JavaScript code; it uses the strict mode for the whole code.

Example

在下面的示例中,我们定义了变量“y”,并将其初始化为 50。该代码在输出中打印 “y” 的值。

In the example below, we have defined the 'y' variable and initialized it with the 50. The code prints the value of 'y' in the output.

另外,我们初始化了变量 “x”,而没有对其进行声明。因此,它在控制台中显示了 error ,并不会打印输出。

Also, we initialized the variable 'x' without declaring it. So, it gives the error in the console and doesn’t print the output.

简而言之,严格模式不允许在未声明变量的情况下就使用该变量。

In short, the strict mode doesn’t allow you to use the variable without its declaration.

<html>
<head>
   <title> Using the strict mode gloablly </title>
</head>
<body>
   <script>
      "use strict";
      let y = 50; // This is valid
      document.write("The value of the X is: " + y);
      x = 100; // This is not valid
      document.write("The value of the X is: " + x);
   </script>
</body>
</html>

Strict Mode in the Local Scope

你还可以将 “严格模式” 用于特定函数中。所以,它只会在函数作用域中生效。我们通过一个示例来理解这一点。

You can also use the "strict mode" inside the particular function. So, it will be applied only in the function scope. Let’s understand it with the help of an example.

Example

在下面的示例中,只在 test() 函数中,才使用了 “use strict” 语法常量。因此,它仅从函数中移除了异常错误。

In the example below, we used the 'use strict' literal only inside the test() function. So, it removes the unusual errors from the function only.

下面的代码允许在函数外部初始化变量,而无需在其内部对其进行声明。

The code below allows you to initialize the variable without declaring it outside the function but not inside it.

<html>
<head>
    <title> Using the strict mode gloablly </title>
</head>
<body>
    <script>
        x = 100; // This is valid
        document.write("The value of the X is - " + x);
        function test() {
            "use strict";
            y = 50; // This is not valid
            document.write("The value of the y is: " + x);
        }
        test();
    </script>
</body>
</html>

Mistakes that you should’t make in the strict mode

  1. You can’t initialize the variable with a value without declaring it.

<script>
   'use strict';
   num = 70.90; // This is invalid
</script>
  1. Similarly, you can’t use the object without declaring it.

<script>
   'use strict';
   numObj = {a: 89, b: 10.23}; // This is invalid
</script>
  1. You can’t delete objects using the delete keyword.

 <script>
   'use strict';
   let women = { name: "Aasha", age: 29 };
   delete women; // This is invalid
</script>
  1. You can’t delete the object prototype in the strict mode.

 <script>
   'use strict';
   let women = { name: "Aasha", age: 29 };
   delete women.prototype; // This is invalid
</script>
  1. Deleting the function using the delete operator is not allowed.

 <script>
   'use strict';
   function func() { }
   delete func; // This is invalid
</script>
  1. You can’t have a function with duplicate parameter values.

<script>
   'use strict';
   function func(param1, param1, param2) {
      // Function with 2 param1 is not allowed!
   }
</script>
  1. You can’t assign octal numbers to variables.

<script>
   'use strict';
   let octal = 010; // Throws an error
</script>
  1. You can’t use escape characters.

<script>
   'use strict';
   let octal = \010; // Throws an error
</script>
  1. You can’t use reserved keywords like eval, arguments, public, etc., as an identifier.

<script>
   'use strict';
   let public = 100; // Throws an error
</script>
  1. You can’t write to the readable property of the object.

<script>
    'use strict';
    let person = {};

    Object.defineProperty(person, 'name', { value: "abc", writable: false });
    obj1.name = "JavaScript"; // throws an error
</script>
  1. You can’t assign values to the getters function.

<script>
   'use strict';
   let person = { get name() { return "JavaScript"; } };
   obj1.name = "JavaScript"; // throws an error
</script>
  1. In the strict mode, when you use the 'this' keyword inside the function, it refers to the reference object through which the function is invoked. If the reference object is not specified, it refers to the undefined value.

<script>
   'use strict';
   function test() {
      console.log(this); // Undefined
   }
   test();
</script>
  1. You can’t use the 'with' statement in the strict mode.

<script>
   'use strict';
   with (Math) {x = sin(2)}; // This will throw an error
</script>
  1. You can’t use the eval() function to declare the variables for the security reason.

<script>
   'use strict';
   eval("a = 8")
</script>
  1. You can’t use the keywords as an identifier that are reserved for the future. Below keywords are reserved for the future −[style="arabic"]

    1. implements

    2. interface

    3. package

    4. private

    5. protected