TypeError:无法读取属性' hello'在JavaScript中未定义

时间:2017-09-26 07:54:17

标签: javascript

您好我正试图在程序下运行。我有一个函数hello,我在b内调用它。它给了我一个错误

  

TypeError:无法读取属性' hello'未定义的

class ChildClass {
  // constructor
  constructor(param, ...args) {

    this.hello = function (a) {
      console.log(a);
    }

    this.obj = {
      a: {
        b() {
          this.hello(2)
        }
      }
    }
  }
}  

有谁知道我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

问题是this并未指向ChildClass实例,而是指向内部a对象。一种解决方案可能是:

class ChildClass {
  // constructor
  constructor(param, ...args) {

    const hello = this.hello = function (a) {
      console.log(a);
    }

    this.obj = {
      a: {
        b() {
         hello(2)
        }
      }
    }
  }
}  

但是,如果您不打算使用hello()作为实例方法,则可以在私有const中声明它并且不要将其放在this上:

class ChildClass {
  // constructor
  constructor(param, ...args) {

    const hello = function (a) {
      console.log(a);
    }

    this.obj = {
      a: {
        b() {
         hello(2)
        }
      }
    }
  }
}  

取决于你想做什么。

或者,您可以将“真实”this保存在const

class ChildClass {
  // constructor
  constructor(param, ...args) {
    const instance = this;

    this.hello = function (a) {
      console.log(a);
    }

    this.obj = {
      a: {
        b() {
         instance.hello(2)
        }
      }
    }
  }
}