TypeScript类继承构造函数混淆
TypeScript class inheritance constructor confusion
我正在阅读《雄辩的Javascript》这本书,我在章节末尾的练习中遇到了一点障碍。我很早就决定,我将主要使用TypeScript在普通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类和继承,所以可能会出现一些新手错误。
扩展类构造函数
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);
- 如何检查DOM节点是否继承自构造函数
- Javascript:继承原型而不重新定义构造函数
- 从类构造函数继承javascript
- JavaScript-构造函数参数和原型继承
- Javascript继承构造函数
- JavaScript继承构造函数.prototype
- 通过父构造函数创建主干继承视图
- JavaScript - 构造函数中的继承
- 构造函数原型-继承混淆
- Crockford 伪经典继承部分中的函数构造函数
- 通过构造函数属性和运算符实例设置继承
- 如何从“构造函数返回另一个对象”对象继承
- 从原型继承与从构造函数继承
- 继承和 TypeScript 错误:X 不是构造函数类型
- 命名空间和继承:具有JavaScript责任链的超级构造函数
- 从另一个构造函数继承会覆盖继承的构造函数的原型链中的现有属性
- 在Javascript中,如何遍历从给定构造函数继承的对象
- 测试主干扩展构造函数继承的好方法是什么?
- 一个构造函数的属性是否可能被另一个构造函数继承?
- javascript构造函数.继承另一个构造函数的原型