Reputation: 378
I've got a class, something like this:
class Server {
constructor() {
this.server = http.createServer(function (req, res) {
this.doSomething()
});
}
doSomething() {
console.log("Working")
}
}
I want to call my doSomething() function from inside the constructor, how can I do this? I've tried doing this.doSomething()
and doSomething()
, both say they are not a function. Also, say in the constructor I did console.log(this.someValue)
, it logs undefined. How can I access the classes own properties/methods? Is it even possible? Thanks.
Upvotes: 0
Views: 55
Reputation: 3731
class Server {
constructor() {
const _this = this;
this.server = http.createServer(function (req, res) {
_this.doSomething()
});
}
doSomething() {
console.log("Working")
}
}
Upvotes: 1
Reputation: 1338
As Yousaf said, all you need to do is use an arrow function instead. Here's an example that shows this in action, using setTimeout
instead of http.createServer
:
class Server {
constructor() {
this.server = setTimeout(() => {
this.doSomething();
}, 0);
}
doSomething() {
console.log("Working");
}
}
new Server();
Upvotes: 1