es6 class类封装方法疑问

用class封装一个方法:

const test=calss{
constructor(){
..
this.init()
}
..
init(){
  
 //return new Promise( function (resolve, reject) {})

}
}

init()放入了constructor,但是当去执行new test(a,b,c).then()会提示.then is not a function,必须constructor里移除this.init(),然后执行new test(a,b,c).init().then()才能正常执行,用什么方法怎样能让它这样new test(a,b,c).then()执行?

阅读 3.8k
3 个回答

return this.init()

因为你确实没有定义then方法,而且不知道你为什么要这样。。

class Test {
  constructor() {
    this.init()
  }

  init() {
    this._promise = new Promise(function(resolve, reject) {
      resolve();
    })
  }

  get then() {
    return this._promise.then.bind(this._promise);
  }
}

new Test().then(a => console.log('a', a))
class Test {
  constructor() {
    return this.init()
  }

  init() {
    return new Promise((resolve, reject) => {
      console.log('I am a text class.')
      resolve();
    })
  }
}

new Test().then(a => console.log('hello world'))

return this.init() 即可

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题