【问题标题】:TypeScript class inheritance constructor confusionTypeScript 类继承构造函数混淆
【发布时间】:2017-03-18 22:18:58
【问题描述】:

我正在阅读 Eloquent Javascript 这本书,但在章节练习结束时遇到了一些障碍。我很早就决定我将主要使用 TypeScript 在 vanilla JS 之上解决这些练习,只是为了让自己接触到 TS 提供给我的额外功能。

完整的练习可以在这里找到:http://eloquentjavascript.net/06_object.html#h_nLNNevzcF7

在我看来,我应该从本质上扩展作者在本章中定义的预先存在的类,我已尽我所能在 TypeScript 中重写以利用类:

//from textbook.

function repeat(string: string, times: number): string {
    var result = '';
    for (var i = 0; i < times; i++)
        result += string;
    return result;
}

//inferred from textbook.

class TextCell {
    text: any;
    constructor(text: string) {
        this.text = text.split('');
    }
    minWidth(): number {
        return this.text.reduce((width: number, line: any) => Math.max(width, line.length), 0);
    }
    minHeight(): number {
        return this.text.length;
    }
    draw(width: number, height: number) : any[]{
        var result: any[] = [];
        for (var i = 0; i < height; i++) {
            var line = this.text[i] || '';
            result.push(line + repeat(' ', width - line.length));
        }
        return result;
    }
}

这是我对该类的扩展:

class StretchCell extends TextCell {
    width:  number;
    height: number;
    constructor(text: any, width: number, height: number) {
        super(text);
        this.width  = width;
        this.height = height;
    }

    minWidth(): number {
        return Math.max(this.width, super.minWidth());
    }
    minHeight(): number {
        return Math.max(this.height, super.minHeight());
    }
    draw(width: number, height: number): any[] {
        return super.draw(this.width, this.height);
    }
}

运行的“测试”是:

var sc = new StretchCell(new TextCell('abc'), 1, 2);

console.log(sc.minWidth());
// → 3
console.log(sc.minHeight());
// → 2
console.log(sc.draw(3, 2));
// → ['abc', '   ']

我目前根本没有得到任何输出,而是得到:TypeError: text.split is not a function。我知道我收到此错误是因为我试图在字符串以外的类型上调用 .split() ,但我不确定在我的代码中的哪个位置 text 被强制转换为不同的类型和导致抛出此错误。

我偷偷怀疑我的问题在于类的构造函数,但我不清楚。任何对我的代码组成的见解将不胜感激。这也是我第一次使用 TypeScript 类和继承,所以期待一些新手错误。

【问题讨论】:

  • 你创建了一个 StretchCell 的实例,第一个参数是一个 TextCell 对象,你的 super 需要一个字符串。在 StretchCell 上,您有 constructor(text: any 是文本还是任何内容。 ?因为你的 super(text) 需要一个字符串。

标签: javascript class oop inheritance typescript


【解决方案1】:

扩展类构造函数中的这段代码

constructor(text: any, width: number, height: number) {
    super(text);

通过调用super(text)text 直接传递给预先存在的类构造函数。所以这里的text 应该是一个字符串,因为它是在预先存在的TextCell 构造函数中声明的。

但是当您创建 StretchCell 类的实例时,您传递的是 TextCell 对象实例,用于 text 参数,而不是字符串。这就是 text.split is not a function 错误的原因 - TextCell 没有名为 split 的方法。

扩展类构造函数应该声明为

constructor(text: string, width: number, height: number) {
    super(text);

StretchCell 实例必须像这样创建:

var sc = new StretchCell('abc', 1, 2);

【讨论】:

    猜你喜欢
    • 2020-01-12
    • 2021-11-06
    • 1970-01-01
    • 2012-09-03
    • 2017-09-19
    • 2012-09-20
    • 2015-01-17
    • 2016-05-16
    相关资源
    最近更新 更多