1,类中
class Dog{ constructor(name, age) { this.name = name this.age = age } cry() { console.log(this) // undefined console.log(`我的名字是${this.name},我的年龄是${this.age}`) } } const d = new Dog('旺财', 10) const x = d.cry x() // 此处属于cry的直接调用,类中所有定义的方法,浏览器在运行时,全部加上了 use strict,这才是this为undefined的原因

2,方法
let obj = { a: 1, b: 2, c: function(){ console.log(this) // this指向window } } const y = obj.c y()
3,严格模式可以局部开启
function a() { 'use strict' console.log(this) // undefined
}
function b() { console.log(this) // window
}
a() b()
4, show()是函数调用表达式
<body>
<div id="test"></div>
</body>
<script type="text/babel">
class Demo extends React.Component {
constructor(props) {
super(props)
this.state = {isHot: true}
}
render() {
const {isHot} = this.state
return <h1 onClick={this.show()}>今天天气很{isHot ? '炎热': '凉爽'}</h1>
}
show(){
console.log(this) //此时this指向Demo的实例对象
}
}
ReactDOM.render(<Demo/>, document.getElementById('test'))
</script>
情况2:react在内部缓存了一个变量x,直接指向show方法(show()属于类原型上的方法),在点击h1的时候,不再通过组件的实例对象调用show方法,而是直接通过x调用show方法,此时启用严格模式,导致this丢失
在点击h1的时候,调用下show函数
<body>
<div id="test"></div>
</body>
<script type="text/babel">
class Demo extends React.Component {
constructor(props) {
super(props)
this.state = {isHot: true}
}
render() {
const {isHot} = this.state
return <h1 onClick={this.show}>今天天气很{isHot ? '炎热': '凉爽'}</h1>
}
show(){
// show函数放在哪里?---Demo的原型对象上,供实例调用
// show函数中的this指向谁?---如果show是通过Demo实例调用,那么this就指向Demo的实例对象
console.log(this) //undefined
}
}
ReactDOM.render(<Demo/>, document.getElementById('test'))
</script>
浙公网安备 33010602011771号