简体   繁体   中英

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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM