You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript继承MemoryStream后status方法为undefined的问题求助

问题分析与解决方案

问题根源

你遇到的问题核心在于memorystream库的MemoryStream构造函数没有返回子类实例的this,而是返回了一个新创建的流对象。当你继承它时,子类FakeResponce调用super()后,实际拿到的实例是MemoryStream构造函数生成的对象,子类原型上定义的status方法不会被挂载到这个返回的对象上,因此通过实例访问status时会得到undefined。

而移除extends MemoryStream时,类的构造函数返回自身实例,原型上的方法能正常被访问,所以status可以正常调用。

你的修复方案评价

你把status改成实例属性并在构造函数里用箭头函数赋值的方式是可行的,但算不上最优:

  • 优点:箭头函数会绑定当前实例的this,且直接挂载在实例对象上,不受父类构造函数返回对象的影响。
  • 缺点:每个FakeResponce实例都会创建一个新的箭头函数,造成内存浪费;同时把方法定义在实例上不符合类方法的常规写法,可读性和维护性稍差。

更优解决方案

可以在子类构造函数中,调用super()拿到父类返回的对象后,通过两种方式修复:

方案1:手动绑定原型方法到实例

import MemoryStream from 'memorystream';

export interface ResponseInterface extends NodeJS.WritableStream{
    status(s: number): ResponseInterface
}

export class FakeResponce extends MemoryStream implements ResponseInterface {
    constructor(){
        const instance = super() as FakeResponce;
        // 将原型上的status方法绑定到父类返回的实例
        instance.status = this.status.bind(instance);
        return instance;
    }

    status(s: number): ResponseInterface{
        console.log("status work!") 
        return this;
    }
}

const a : ResponseInterface = new FakeResponce();
console.log(`status is ${a.status}`);
a.status(200); // 正常调用

方案2:修正实例的原型链指向

import MemoryStream from 'memorystream';

export interface ResponseInterface extends NodeJS.WritableStream{
    status(s: number): ResponseInterface
}

export class FakeResponce extends MemoryStream implements ResponseInterface {
    constructor(){
        const instance = super();
        // 将实例的原型指向子类原型,使其能访问子类的方法
        Object.setPrototypeOf(instance, FakeResponce.prototype);
        return instance;
    }

    status(s: number): ResponseInterface{
        console.log("status work!") 
        return this;
    }
}

const a : ResponseInterface = new FakeResponce();
console.log(`status is ${a.status}`);
a.status(200); // 正常调用

这两种方案都能让status作为类方法存在(仅在原型上创建一次),避免了每个实例重复创建函数的问题,也符合类的常规写法。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 08:23:32