2016-11-05 8 views
2

私は本Eloquent Javascriptを使って作業していますが、私は章の終わりの演習で少し突っ込んできました。私は早くTypeScriptを使って、バニラJSの上でこれらの演習に取り組み、TSが私に与える特別な機能に自分自身をさらけ出すことに決めました。 TypeScriptクラスの継承コンストラクタの混乱

いっぱい運動

はここで見つけることができます:私はそれを見るように、私は基本的に私は自分のベストを行っている、この章の中の著者によって定義されている既存のクラスを拡張することになってる http://eloquentjavascript.net/06_object.html#h_nLNNevzcF7

//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); 
    } 
} 

その「テスト」をするクラスを活用する活字体で再書き込みへ実行されている:TypeError: text.split is not a functionを:

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', ' '] 

私は現在、代わりに私が取得しています、まったくの出力が届きません。文字列以外の型で.split()を呼び出そうとしているのでこのエラーが発生していることはわかっていますが、textが別の型に強制され、エラーがスローされます。

私の問題はクラスのコンストラクタの中にあることが疑わしいですが、私には不明です。私のコードの構成についての洞察は非常に高く評価されます。これはTypeScriptクラスと継承を初めて使用したので、初心者の間違いがあります。拡張クラスのコンストラクタで

+0

あなたがStretchCellのインスタンスを作成し、最初のパラメータはTextCellオブジェクトです、あなたのスーパーは文字列を期待しています。あなたのスーパー(テキスト)は文字列を期待しているので、StretchCellで 'コンストラクタ(text:anyはそのテキストですか? – Keith

答えて

4

このコードは

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

super(text)を呼び出すことにより、既存のクラスのコンストラクタに直接textを渡します。したがってtextは文字列であると仮定されています。これは既存のTextCellコンストラクタで宣言されているためです。

しかし、StretchCellクラスのインスタンスを作成するときは、textパラメータのオブジェクトインスタンスであるTextCellを渡しています。文字列ではありません。これが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); 
関連する問題