this 为undefined的情况
首先我们要知道
在严格模式下,独立function中的this指向为undefined;非严格模式指向为全局作用域。
而在es6的类
当中:
首先明确的是类中所有定义的方法,在浏览器运行时候全部都加上了
user strict
,何为user strict
,就是浏览器的严格模式。那第二个问题就来了,为什么在严格模式下就为undefined。严格模式下无法再意外创建全局变量
记住这点就可以了
'use strict'
function a() {
b()
function b() {
console.log(this);
}
}
a()//undefined
如果不使用'use strict'
,打印的就是指向window
看看类
class Person {
constructor(name) {
this.name = name
this.init()
this.geter()
}
init() {
console.log(this);
}
geter() {
function success() {
console.log(this);
}
success()
/* 这里是在没有严格模式的情况下是window来调用,但严格模式下没有window,所以
是undefined */
}
}
let jack = new Person('jack')