示例1
<!DOCTYPE html><html lang="en"><body><button id="commonBtn">common btn</button><button id="arrowBtn">arrow btn</button><button id="bindFn">arrow btn</button><script>class Obj {constructor() {this.state = {type: 'account'}this.getThisWithBind = this.getThisWithBind.bind(this)}getThis() {console.log(this, "---common fn---")}getThisWithArrow = () => {console.log(this, "---arrow fn---")}getThisWithBind() {console.log(this, "---bind fn---")}}const myObj = new Obj();/*** 关键在这里,参看阮一峰的this指向blog* http://www.ruanyifeng.com/blog/2018/06/javascript-this.html*/const commonFn = myObj.getThisconst arrowFn = myObj.getThisWithArrowconst bindFn = myObj.getThisWithBinddocument.querySelector('#commonBtn').addEventListener('click', commonFn)document.querySelector('#arrowBtn').addEventListener('click', arrowFn)document.querySelector('#bindFn').addEventListener('click', bindFn)</script></body></html>

- 普通方法的this指向变成了事件对象
- 箭头函数的this指向和bind后的一样还是这个类对象
示例2
class A {
constructor() {
this.x = 1;
}
}
class B extends A {
constructor() {
super();
this.x = 2;
console.log(this); // B
// this.getme = this.getme.bind(this)
}
getName() {
console.log(this, "====="); // B
let m = this.getme
m()
}
getme() {
console.log(this, "-----"); // undefined
}
}
let b = new B();
b.getName()
这里变成了 undefined
let m = this.getme
m()
将方法进行赋值之后,丢失了上下文,导致 this 变成 undefined ,
这个方法提出来单独使用,this会指向该方法运行时所在的环境(ES6标准入门 p411),
this之所以没有变为window 是因为类声明和类表达式的主体以 严格模式 执行,主要包括构造函数、静态方法和原型方法。Getter 和 setter 函数也在严格模式下执行。
参考
阮一峰es6标准入门
http://es6.ruanyifeng.com/#docs/class#%E6%B3%A8%E6%84%8F%E7%82%B9
阮一峰this指向
http://www.ruanyifeng.com/blog/2018/06/javascript-this.html
