Yankue
Yankue

Reputation: 378

Access own properties in Javascript constructor?

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

Answers (2)

Adrian
Adrian

Reputation: 3731

class Server {
    constructor() {
        const _this = this;
        this.server = http.createServer(function (req, res) {
            _this.doSomething()
        });
    }

    doSomething() {
        console.log("Working")
    }
}

Upvotes: 1

Nisala
Nisala

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

Related Questions