0

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.

3
  • 1
    this.doSomething() will call it. If you get an error, post the code that produces that error Commented May 11, 2021 at 18:45
  • I have now found the issue, the this is referring to the callback function on the HTTP server. Is there a way I can almost "go up 1 level" with this keyword? Commented May 11, 2021 at 18:51
  • 1
    use an arrow function: http.createServer((req, res) => { ... } Commented May 11, 2021 at 18:54

2 Answers 2

1

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();

Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.