javascript - 在 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)
,它记录未定义。如何访问类自己的属性/方法?甚至可能吗?谢谢。
解决方案
class Server {
constructor() {
const _this = this;
this.server = http.createServer(function (req, res) {
_this.doSomething()
});
}
doSomething() {
console.log("Working")
}
}
推荐阅读
- python - 如何使用 OpenCV 检测反转颜色(0 和 255)图像中的轮廓?
- javascript - 反应:设置状态清除表单提交上的输入
- node.js - 嵌套循环对 Node.js 中的每条记录进行续集
- android - 如何在 exoplayer 中设置质量轨道的最大高度和最小高度
- html - 将背景颜色应用于网格之间的间隙
- babeljs - swiperjs es 模块构建在 IE11 浏览器中不起作用
- liferay - Liferay 7.2 DXP 中的 Bean Portlet
- makefile - centos中如何提高make和make install的速度?
- maven - NetBeans 无法识别依赖项是本地项目 - 如何修复?
- python - 如何在循环中过滤多个数据帧?