You need to enable JavaScript to run this app. 如何在JavaScript类的constructor中访问类自身的属性与方法
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript类的constructor中访问类自身的属性与方法

问题原因

  • 你遇到的报错本质是普通函数的this指向丢失问题:http.createServer的回调使用普通函数声明时,运行时this会绑定到Node.js内部的HTTP服务器实例上下文,而非你定义的Server类的实例,所以this.doSomething()会找不到方法。
  • 直接写doSomething()会从全局作用域查找该方法,自然也会报错。
  • 打印this.someValue为undefined,是因为你没有提前给实例的someValue属性赋值,未定义的实例属性默认返回undefined。

解决方案

下面是三种常用的修复方式,任选一种即可:

方式1:使用箭头函数作为回调(最推荐)

箭头函数不会创建自己的this,会继承外层作用域的this指向,也就是Server类的实例:

const http = require('http');

class Server {
    constructor() {
        // 先给属性赋值才能正常访问
        this.someValue = '自定义属性值';
        console.log(this.someValue); // 正常输出:自定义属性值

        // 回调改用箭头函数
        this.server = http.createServer((req, res) => {
            this.doSomething(); // 正常调用实例方法
        });
    }

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

方式2:提前保存外层this到变量

ES6之前的通用兼容方案,提前把类实例的this存到局部变量,回调内直接使用该变量访问实例成员:

const http = require('http');

class Server {
    constructor() {
        const self = this; // 保存类实例的this
        this.server = http.createServer(function (req, res) {
            self.doSomething(); // 通过self访问实例方法
        });
    }

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

方式3:给回调函数绑定this

使用bind方法强制把回调的this绑定为当前类实例:

const http = require('http');

class Server {
    constructor() {
        this.server = http.createServer(function (req, res) {
            this.doSomething();
        }.bind(this)); // 绑定this为类实例
    }

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

如果你只是要在constructor的非回调逻辑里直接调用类方法,不需要处理指向问题,直接写this.doSomething()就可以正常执行。

内容的提问来源于stack exchange,提问作者Yankue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 13:15:04