JavaScript “use strict“(严格模式)

x33g5p2x  于2022-05-23 转载在 Java  
字(2.3k)|赞(0)|评价(0)|浏览(198)

在本教程中,您将借助示例了解 JavaScript 的“严格模式”语法。
    在 JavaScript 中,‘use strict’; 声明代码应该在“严格模式”下执行。这使得编写良好且安全的 JS 代码变得更加容易。例如,

myVariable = 9;

这里,myVariable 是在没有声明的情况下创建的,在 JavaScript 中用作全局变量。但是,如果在严格模式下使用它,程序会抛出错误。例如,

'use strict';

// Error
myVariable = 9;

上面的代码会抛出错误,因为 myVariable 未声明。在严格模式下,您不能在不声明变量的情况下使用它们。
    为了表明该程序处于严格模式,我们在程序的顶部使用了:

'use strict';

您可以通过在程序开头添加 ‘use strict’; 或 “use strict”; 来声明严格模式。
    当您在程序开始声明严格模式时,它将具有全局范围,并且程序中的所有代码都将在严格模式下执行。

变量的严格模式

在严格模式下,使用变量而不声明变量会引发错误。
    注意:您需要在程序开始时声明严格模式。如果您在某些代码下面声明严格模式,它将不起作用。例如,

console.log("some code");

// 'use strict' is ignored
// must be at the top
"use strict";

x = 21; // does not throw an error
函数的严格模式

您还可以在函数内使用严格模式。例如,

myVariable = 9;
console.log(myVariable); // 9

function hello() {

    // applicable only for this function
    'use strict';

    string = 'hello'; // throws an error
}

hello();

如果在函数内部使用 ‘use strict’; ,函数内部的代码将处于严格模式。在上面的程序中,hello() 函数里面用到了 ‘use strict’; 。因此,严格模式仅适用于函数内部。
    如您所见,在程序的开头,myVariable 没有声明就使用了。
    如果在程序的顶部声明 ‘use strict’; ,在使用变量之前一定要在函数内部声明它。例如,

// applicable to whole program
'use strict';

function hello() {
    string = 'hello'; // throws an error
}

hello();

注意:严格模式不适用于带大括号 { } 的块语句。

严格模式下不允许的事情
  1. 不允许未声明的变量。
'use strict';

a = 'hello'; // throws an error
  1. 不允许未声明的对象。
'use strict';

person = {name: 'Carla', age: 25}; // throws an error
  1. 不允许删除对象。
'use strict';

let person = {name: 'Carla'};

delete person; // throws an error
  1. 不允许重复参数名称。
"use strict";

function hello(p1, p1) { console.log('hello')}; // throws an error

hello();
  1. 不允许分配给不可写属性。
'use strict';

let obj1 = {};

Object.defineProperty(obj1, 'x', { value: 42, writable: false });

// assignment to a non-writable property
obj1.x = 9; // throws an error
  1. 不允许分配给 getter-only 属性。
'use strict';

let obj2 = { get x() { return 17; } };

// assignment to a getter-only property
obj2.x = 5; // throws an error
  1. 不允许在不可扩展的对象上指定新属性。
'use strict';

let obj = {};
Object.preventExtensions(obj);

// Assignment to a new property on a non-extensible object
obj.newValue = 'new value'; // throws an error
  1. 不允许使用八进制语法。
'use strict';

let a = 010; // throws an error
  1. 不允许使用变量名参数和 eval。
'use strict';

let arguments = 'hello'; // throws an error

let eval = 44;
  1. 您也不能在严格模式下使用这些保留关键字。
    implements interface let package private protected public static yield
严格模式的好处

严格模式的使用:

  • 有助于编写更简洁的代码
  • 将以前接受的静默错误(错误语法)更改为实际错误并抛出错误消息
  • 更容易编写“安全”的 JavaScript

上一教程 :JS this                                          下一教程 :Iterators and Iterables

参考文档

[1] Parewa Labs Pvt. Ltd. (2022, January 1). Getting Started With JavaScript, from Parewa Labs Pvt. Ltd: https://www.programiz.com/javascript/use-strict

相关文章

微信公众号

最新文章

更多