I have a class with define variable in the constructor, this class has a method that prints the value of the variable. So far so good. I call the class and the result is as expected. However, when I call the class in a promisse, the variable this does not exist. Could someone help me with this? Here is the code:
This code retur correct result
class classTest {
constructor() {
this._value = 'Value in constructor';
}
func() {
return new Promise((resolve, reject) => {
console.log(this._value);
resolve();
});
}
};
let test = new classTest();
test.func();
This code retur TypeError: Cannot read property '_value' of undefined
class classTest {
constructor() {
this._value = 'Value in constructor';
}
func() {
return new Promise((resolve, reject) => {
console.log(this._value);
resolve();
});
}
};
let test = new classTest();
const p = new Promise((resolve, reject) => {
resolve()
});
p
.then(test.func)
.catch(console.error);