url = 'http://task.lmcjl.com/';
),此时 JavaScript 解释器会自动为您创建这个变量。为了使代码更加严谨,JavaScript 中引入了严格模式,一旦使用了严格模式,将不再允许使用那些不严谨的语法。 "use strict";
或 'use strict';
指令即可,如下所示:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript</title> </head> <body> <script> "use strict"; x = 'http://c.binacheng.net/'; // 此处报错:Uncaught ReferenceError: x is not defined at index.html:11 console.log(x); </script> </body> </html>如果将
"use strict";
指令添加到 JavaScript 程序的第一行,则表示整个脚本都会处于严格模式。如果在函数的第一行代码中添加 "use strict";
,则表示只在该函数中启用严格模式。如下例所示:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JavaScript</title> </head> <body> <script> x = 'http://c.binacheng.net/'; console.log(x); function sayHello(){ 'use strict'; str = 'welcome http://c.binacheng.net/'; // 调用 sayHello() 函数在此处报错:Uncaught ReferenceError: str is not defined at sayHello (index.html:14) at index.html:17 console.log(str); } sayHello(); </script> </body> </html>
注意:"use strict";
或 'use strict';
指令只有在整个脚本第一行或者函数第一行时才能被识别,除了 IE9 以及更低的版本外,所有的浏览器都支持该指令。
"use strict"; v = 1; // 此处报错:Uncaught ReferenceError: v is not defined for(i = 0; i < 2; i++) { // 此处报错:Uncaught ReferenceError: i is not defined }
"use strict"; var person = {name: "Peter", age: 28}; delete person; // 此处报错:Uncaught SyntaxError: Delete of an unqualified identifier in strict mode. function sum(a, b) { return a + b; } delete sum; // 此处报错:Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.
"use strict"; function square(a, a) { // 此处报错:Uncaught SyntaxError: Duplicate parameter name not allowed in this context return a * a; }
"use strict"; eval("var x = 5; console.log(x);"); console.log(x); // 此处报错:Uncaught ReferenceError: x is not defined
"use strict"; var radius1 = 5; var area1 = Math.PI * radius1 * radius1; var radius2 = 5; with(Math) { // 此处报错:Uncaught SyntaxError: Strict mode code may not include a with statement var area2 = PI * radius2 * radius2; }
"use strict"; var person = {name: "Peter", age: 28}; Object.defineProperty(person, "gender", {value: "male", writable: false}); person.gender = "female"; // 此处报错:Uncaught TypeError: Cannot assign to read only property 'gender' of object '#<Object>'
"use strict"; var x = 010; // 此处报错:Uncaught SyntaxError: Octal literals are not allowed in strict mode. console.log(parseInt(x));
"use strict"; //如果在if语句中声明函数,则会产生语法错误 if (true) { function demo() { // 此处报错:Uncaught ReferenceError: demo is not defined console.log("http://task.lmcjl.com/"); } } demo();
"use strict"; var name = "http://task.lmcjl.com/"; function demoTest() { console.log(this); } demoTest();
本文链接:http://task.lmcjl.com/news/17883.html