ES6 class类中方法this丢失为什么打印undefined而非Window?

Chrome环境下运行:

class Cat {
 sayThis () {
     console.log(this);
 }
 exec (cb) {
     cb();
 }
 render () {
     this.exec(this.sayThis);
 }
}
const tom = new Cat();
tom.render(); 

下意识的认为会打印 Window
但是却打印出 undefined
具体是什么原因造成的呢?

回复
阅读 5.3k
5 个回答

原因是es6为严格模式, 在函数内部不会乱指window的

类里面的方法 类似箭头函数

class C {
  xxx(){}
}

等同于

'use strict'
function C() {}
C.prototype.xxx = function() {}
class Cat {
  sayThis () {
    console.log('结果', this)
  }
    
  // 此时接收的是一个新函数,使用bind call apply 都可解决
  exec (cb) {
    cb()
  }
  
  render () {
    this.exec(this.sayThis.bind(this));
  }
}
const tom = new Cat();
tom.render();
新手上路,请多包涵
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏