【发布时间】: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