严格模式不仅可以用在全局,还能用在局部。
当在严格模式下,this不会指向window
两个简单函数,对比局部严格模式和非严格模式下的两种this指向
function f(){
console.log(this)
}
function f2(){
'use strict'
console.log(this)
}
f();
f2();
执行结果:
可见:
局部严格模式下的this值为undefined
在ES6的类定义中,类的内部默认是严格模式,即其中函数的this指向默认是undefined,在React类组件状态改变时会涉及函数this的指向问题
//1.创建组件
class MyComponent extends React.Component{
constructor(props){
super(props)
this.state={isHot=true}
//实例方法=原型链上的weatherChange绑定给实例对象得到新的函数(新函数的this指向实例)
this.change=this.weatherChange.bind(this)
}
render(){
return <h1 onClick="change">The weather is {isHot?'hot':'cold'}</h1>
}
//3.修改状态
weatherChange(){
const isHot=this.state.isHot
//通过内置的api去更改状态,且更新是合并,不是替换(即原来的属性不变)
this.setState({isHot:!isHot})
//this.state.isHot=this.state.isHot?false:true
}
}
//2.渲染组件
ReactDOM.render(<MyComponent/>,getElementById('root'));