class MPromise {
constructor(handle) {
this._status = PENDDING
this._value = null
this.callBackFuncs = []
this.rejCallBackFuncs = []
handle(this._resolve, this._reject)
}
_resolve(val) {
console.log(this)
if (this._status !== PENDDING) return
this._status = FULLFILLED
this._value = val
this.callBackFuncs.forEach(fn => {
fn()
})
}
_reject() {
if (this._status !== PENDDING) return
this._status = REJECTED
this.rejCallBackFuncs.forEach(fn => {
fn()
})
}
then(onFulFilled) {
if (this._status === PENDDING) {
this.callBackFuncs.push(onFulFilled)
}
if (this._status === FULLFILLED) {
onFulFilled()
}
}
}
new MPromise((resolve, reject) => {
resolve()
})
为什么这段代码打印出来的this是undefined,这里不是匿名函数调用吗,不应该是window吗### 问题描述
问题出现的环境背景及自己尝试过哪些方法
相关代码
粘贴代码文本(请勿用截图)
你期待的结果是什么?实际看到的错误信息又是什么?
###Class 是es6的语法,默认启动的是严格模式;严格模式下this是指向 undefined 的;
class MPromise {
constructor(handle) {
this._status = 'PENDDING'
this._value = null
this.callBackFuncs = []
this.rejCallBackFuncs = []
handle(this._resolve.bind(this),this._reject.bind(this))
}
_resolve(val) {
console.log(this)
if (this._status !== 'PENDDING') return
this._status = 'FULLFILLED'
this._value = val
this.callBackFuncs.forEach(fn => {
fn()
})
}
_reject() {
if (this._status !== 'PENDDING') return
this._status = 'REJECTED'
this.rejCallBackFuncs.forEach(fn => {
fn()
})
}
then(onFulFilled) {
if (this._status === 'PENDDING') {
this.callBackFuncs.push(onFulFilled)
}
if (this._status === 'FULLFILLED') {
onFulFilled()
}
}
}
new MPromise((resolve, reject) => {
resolve()
})
###
ES5增加了严格模式,即user strict
,这种模式下无主的this为undefined,而不再是window。
使用ES6语法将默认开启严格模式
把你上面的代码转换为ES5的写法,this就会指向window了
###在ES6 class 中默认是严格模式,严格模式下普通调用指向 undefined