Reputation: 34497
Hi I am trying to run below program. I have one function hello
and I am calling it inside b
. It gives me an error
TypeError: Cannot read property 'hello' of undefined
class ChildClass {
// constructor
constructor(param, ...args) {
this.hello = function (a) {
console.log(a);
}
this.obj = {
a: {
b() {
this.hello(2)
}
}
}
}
}
Does anyone know what I am doing wrong here ?
Upvotes: 0
Views: 266
Reputation: 2119
The problem is that this
isn't pointing to the ChildClass
instance but to the inner a
object. One solution might be:
class ChildClass {
// constructor
constructor(param, ...args) {
const hello = this.hello = function (a) {
console.log(a);
}
this.obj = {
a: {
b() {
hello(2)
}
}
}
}
}
However if you don't intend to use hello()
as an instance method, you can simply declare it in a private const
and don't put it on this
:
class ChildClass {
// constructor
constructor(param, ...args) {
const hello = function (a) {
console.log(a);
}
this.obj = {
a: {
b() {
hello(2)
}
}
}
}
}
Depends on what you want to do.
Or, you can save the "real" this
in a const
:
class ChildClass {
// constructor
constructor(param, ...args) {
const instance = this;
this.hello = function (a) {
console.log(a);
}
this.obj = {
a: {
b() {
instance.hello(2)
}
}
}
}
}
Upvotes: 1