文章目录
1,开启严格
所有语句之前,或者函数开头。
"use strict";
a=3;
效果:
开启前。
开启后。
2,严格的变化一:报错
声明不带var,let,const
x = 3.14;
使用delete,with
var x = 3.14;
delete x;
with (Math){x = cos(2)};
参数,属性重名
function x(p1, p1) {};
let a={
name:1,
name:1
}
八进制
var x = 010;
3,严格的变化二:this
全局的,指向window
<script>
"use strict";
console.log(this)
</script>
全局的函数中,指向undefined
<script>
"use strict";
function f() {
console.log(this)
}
f()
</script>
对象的方法中,指向该对象
<script>
"use strict";
let a={
say(){
console.log(this)
}
}
a.say()
</script>
构造函数,指向该对象
<script>
"use strict";
function A() {
console.log(this)
}
new A()
</script>
事件处理函数中,指向触发者
<button id="app">按钮</button>
<script>
"use strict";
let app=document.getElementById("app")
app.onclick=function (e) {
console.log(this)
}
</script>
小结
- 全局,window
- 全局函数,undefined
- 对象方法,该对象
- 构造函数,该对象
- 事件处理函数,触发者
思考:React事件处理函数中undefined
函数的作用域是由调用方决定的,比如:
var name = 'globalName';
var obj = {
name: 'objName',
getName: function() {
return this.name;
}
};
var getName = obj.getName;
obj.getName(); // objName
getName(); // globalName,严格undefined
在React中:
直接调this.handleClick():没有问题。
调用onClick():undefined。
onClick是在App外部被调用的。
class App extends Component {
handleClick () {
// ...
}
render () {
return <div onClick={this.handleClick}></div>;
}
}