首页 > 解决方案 > 在 Javascript 构造函数中访问自己的属性?

问题描述

我有一堂课,是这样的:

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

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

我想从构造函数内部调用我的 doSomething() 函数,我该怎么做?我试过做this.doSomething()and doSomething(),都说它们不是函数。另外,在我做的构造函数中说console.log(this.someValue),它记录未定义。如何访问类自己的属性/方法?甚至可能吗?谢谢。

标签: javascriptclassconstructor

解决方案


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

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

推荐阅读