您的位置:首页 > Web前端 > JavaScript

JavaScript 严格模式(use strict)

2017-08-21 18:08 375 查看
1.”use strict” 的目的是指定代码在严格条件下执行。严格模式下你不能使用未声明的变量。

注意:

支持严格模式的浏览器:

Internet Explorer 10 +、 Firefox 4+ Chrome 13+、 Safari 5.1+、 Opera 12+。

<script>
"use strict";
x = 3.14;       // 报错 (x 未定义)
</script>


2.在函数内部声明是局部作用域 (只在函数内使用严格模式):

<script>
"use strict";
myFunction();
function myFunction() {
y = 3.14;   // 报错 (y 未定义)
}


<script>
x = 3.14;       // 不报错
myFunction();
function myFunction() {
"use strict";
y = 3.14;   // 报错 (y 未定义)
}


3.严格模式的限制

不允许使用未声明的变量或对象:

"use strict";
x = 3.14;                // 报错 (x 未定义)


不允许删除变量、对象或函数:

"use strict";
var x = 3.14;
delete x;


"use strict";
function x(p1, p2) {};
delete x;
// 报错


不允许变量重名:

"use strict";
function x(p1, p1) {};
// 报错


不允许使用八进制:

"use strict";
var x = 010;
// 报错


不允许使用转义字符:

"use strict";
var x = \010;
// 报错


以下需注意,详述在后面的章节!

不允许对只读属性赋值:

"use strict";
var obj = {};
Object.defineProperty(obj, "x", {value:0, writable:false});

obj.x = 3.14;
// 报错


不允许对一个使用getter方法读取的属性进行赋值:

"use strict";
var obj = {get x() {return 0} };

obj.x = 3.14;
// 报错


不允许删除一个不允许删除的属性:

"use strict";
delete Object.prototype; // 报错


变量名不能使用 “eval”、”arguments” 字符串:

"use strict";
var eval = 3.14;
// 报错


"use strict";
var arguments = 3.14;
// 报错


不允许使用以下这种语句:

"use strict";
with (Math){x = cos(2)};
// 报错


由于一些安全原因,在作用域 eval() 创建的变量不能被调用:

"use strict";
eval ("var x = 2");
alert (x);
// 报错


禁止this关键字指向全局对象:

function f(){
return !this;
}
// 返回false,因为"this"指向全局对象,"!this"就是false

function f(){
"use strict";
return !this;
}
// 返回true,因为严格模式下,this的值为undefined,所以"!this"为true。


因此,使用构造函数时,如果忘了加new,this不再指向全局对象,而是报错。

<script>
function test()
{
"use strict";
this.x=1;
}
test();//报错
alert(x);
</script>


正确:

<script>
function test()
{
"use strict";
this.x=1;
}
var y=new test();
alert(y.x);
</script>


不允许使用保留字:

implements
interface
let
package
private
protected
public
static
yield
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: