【问题标题】:TypeError: Cannot read property 'hello' of undefined in JavaScriptTypeError:无法读取 JavaScript 中未定义的属性“你好”
【发布时间】:2017-09-26 15:59:35
【问题描述】:

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

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

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

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

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

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

【问题讨论】:

标签: javascript


【解决方案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)
        }
      }
    }
  }
}  

【讨论】:

    猜你喜欢
    • 2017-06-29
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2015-06-08
    • 1970-01-01
    相关资源
    最近更新 更多