Chrome环境下运行:
class Cat {
sayThis () {
console.log(this);
}
exec (cb) {
cb();
}
render () {
this.exec(this.sayThis);
}
}
const tom = new Cat();
tom.render();
下意识的认为会打印 Window
但是却打印出 undefined
具体是什么原因造成的呢?
Chrome环境下运行:
class Cat {
sayThis () {
console.log(this);
}
exec (cb) {
cb();
}
render () {
this.exec(this.sayThis);
}
}
const tom = new Cat();
tom.render();
下意识的认为会打印 Window
但是却打印出 undefined
具体是什么原因造成的呢?
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();
16 回答2.8k 阅读✓ 已解决
6 回答4k 阅读✓ 已解决
9 回答3.4k 阅读✓ 已解决
14 回答5.2k 阅读
6 回答3k 阅读✓ 已解决
7 回答1.7k 阅读
14 回答2k 阅读
原因是es6为严格模式, 在函数内部不会乱指window的