我有一堂课,是这样的:
class Server {
constructor() {
this.server = http.createServer(function (req, res) {
this.doSomething()
});
}
doSomething() {
console.log("Working")
}
}
我想从构造函数内部调用我的 doSomething() 函数,我该怎么做?我试过做 this.doSomething()
和 doSomething()
,都说它们不是函数。另外,在构造函数中说我做了 console.log(this.someValue)
,它记录未定义。如何访问类自己的属性/方法?甚至有可能吗?谢谢。
答案 0 :(得分:1)
正如 Yousaf 所说,您需要做的就是改用箭头函数。下面是一个示例,它使用 setTimeout
而不是 http.createServer
:
class Server {
constructor() {
this.server = setTimeout(() => {
this.doSomething();
}, 0);
}
doSomething() {
console.log("Working");
}
}
new Server();