下面是一个使用JavaScript严格模式的代码示例。在这个示例中,我将展示如何在整个脚本中启用严格模式,并演示一些严格模式下可能遇到的问题。
"use strict";
a = 1; // Uncaught ReferenceError: a is not defined
// 尝试使用一个未声明的变量
// 在严格模式下,这将抛出一个 ReferenceError
// var undeclaredVariable;
console.log(undeclaredVariable); // ReferenceError: undeclaredVariable is not defined
// 尝试删除一个变量
var declaredVariable = "Hello, World!";
delete declaredVariable; // SyntaxError: Identifier 'declaredVariable' can't be deleted
console.log(declaredVariable); // "Hello, World!"
// 尝试使用八进制字面量
var octalLiteral = 010; // SyntaxError: Octal literals are not allowed in strict mode.
// 尝试修改 this 的值
function exampleFunction() {
return this;
}
var obj = { prop: 42 };
var func = exampleFunction.bind(obj);
func.this