Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

严格模式不详解 #13

Closed
rottenpen opened this issue Jan 28, 2019 · 1 comment
Closed

严格模式不详解 #13

rottenpen opened this issue Jan 28, 2019 · 1 comment

Comments

@rottenpen
Copy link
Owner

rottenpen commented Jan 28, 2019

变量必须声明之后再使用

这个好理解,下一个。

函数得参数不能有同名属性,否则报错

function c(b, b) { return b }
c(1, 2) // 2 

"use strict"
function cd(b, b) { return b } // 严格模式下报错
// Duplicate parameter name not allowed in this context

实际上,使用 es6 函数语法的时候无论是否严格模式 ,这一条都成立。

let  a = (b, b) => b // 箭头函数不管有没严格模式都是不允许同名属性得
// Uncaught SyntaxError: Duplicate parameter name not allowed in this context

// 使用默认参数的时候也会报错
// 不报错
function foo(x, x, y) {
  // ...
}

// 报错
function foo(x, x, y = 1) {
  // ...
}
// SyntaxError: Duplicate parameter name not allowed in this context

不能使用 with 语法

我也没用过 with 语法:)
所以搜索了点资料。为什么不用 with 呢?主要是性能问题。发现在 vue2 里尤大也有用到它 with

// 示例代码:
var foo = 1;
var bar = {
    foo : 2
}
with (bar) {
    alert(foo);
    foo = 3;
    alert(foo);
    var foo = 4;
    alert(foo)
}
alert(bar.foo);
alert(foo);
if(true){
    foo = 5;
}
alert(foo);
// 2, 3, 4, 4, 1, 5

简单来说如果 foo 在 bar 里,就会对 bar 里的 foo 进行修改,而全局的 foo 不会发生修改。
如果 with 里的变量,在 with 定义的局部环境里没有,就会上升到高一层的环境寻找,而且会对其进行修改。

var foo = 1
var bar = {}
with(bar) {console.log(foo); var foo = 3 }
console.log(foo); 
// 1, 3

不能对只读属性进行赋值,否则报错

只读属性,包括 const,Object.defineProperty 的 writable: false。
另外,对一个使用 getter 方法读取的属性进行赋值,会报错。

不能使用前缀 0 表示八进制数,否则报错。

"use strict"
var a = 0100
// Uncaught SyntaxError: Octal literals are not allowed in strict mode.

如果想要使用八进制数字,可以使用 es6 的新语法。
二进制 0b,0B
八进制 0o,0O => 0o100
十六进制 0x,0X(不是 es6 的)

@rottenpen
Copy link
Owner Author

rottenpen commented Jan 28, 2019

不能删除不可删除的属性,否则报错

"use strict";
delete Object.prototype; // 报错
Uncaught TypeError: Cannot delete property 'prototype' of function Object() { [native code] }

不能删除变量 delete prop,会报错,只能删除属性 delete global[prop]

eval 不会在它的外层作用域引入变量 && eval 和 arguments 不能被重新赋值

由于eval()函数过于强大,严格模式对其进行了严格的限制
不能通过eval()函数来创建变量或函数,但可以查询和更改其值

arguments 不会自动反映函数参数的变化

不能使用 arguments.callee

当一个函数必须调用自身的时候, 避免使用 arguments.callee(), 通过要么给函数表达式一个名字,要么使用一个函数声明.

不能使用 arguments.caller

本属性已被移除且不再有用。

禁止 this 指向全局对象

字面意思。

不能使用 fn.callerfn.arguments 获取函数调用的堆栈

fn.caller 非标准,fn.arguments已弃用

增加了保留字(比如 protected、static 和 interface)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant