Typescript-classes

提供:Dev Guides
移動先:案内検索

TypeScript-クラス

TypeScriptはオブジェクト指向のJavaScriptです。 TypeScriptは、クラス、インターフェイスなどのオブジェクト指向プログラミング機能をサポートしています。 OOPに関するクラスは、オブジェクトを作成するための青写真です。 クラスは、オブジェクトのデータをカプセル化します。 Typescriptは、クラスと呼ばれるこの概念の組み込みサポートを提供します。 JavaScript ES5以前はクラスをサポートしていませんでした。 TypescriptはES6からこの機能を取得します。

クラスを作成する

classキーワードを使用して、TypeScriptでクラスを宣言します。 同じための構文は以下のとおりです-

構文

class class_name {
  //class scope
}

classキーワードの後に​​クラス名が続きます。 クラスに名前を付けるときは、識別子の規則を考慮する必要があります。

クラス定義には、次のものを含めることができます-

  • フィールド-フィールドは、クラスで宣言された変数です。 フィールドはオブジェクトに関するデータを表します
  • コンストラクタ-クラスのオブジェクトにメモリを割り当てる責任があります
  • 関数-関数はオブジェクトが実行できるアクションを表します。 また、メソッドと呼ばれることもあります

これらのコンポーネントをまとめて、クラスのデータメンバーと呼びます。

タイプスクリプトのクラスPersonを考えてください。

class Person {
}

コンパイル時に、次のJavaScriptコードが生成されます。

//Generated by typescript 1.8.10
var Person = (function () {
   function Person() {
   }
   return Person;
}());

例:クラスの宣言

class Car {
  //field
   engine:string;

  //constructor
   constructor(engine:string) {
      this.engine = engine
   }

  //function
   disp():void {
      console.log("Engine is  :   "+this.engine)
   }
}

この例では、クラスCarを宣言しています。 クラスにはengineという名前のフィールドがあります。 var キーワードは、フィールドの宣言中には使用されません。 上記の例では、クラスのコンストラクターを宣言しています。

コンストラクターは、クラスの変数の初期化を担当するクラスの特別な関数です。 TypeScriptは、constructorキーワードを使用してコンストラクターを定義します。 コンストラクターは関数であるため、パラメーター化できます。

*this* キーワードは、クラスの現在のインスタンスを参照します。 ここで、パラメーター名とクラスのフィールドの名前は同じです。 したがって、あいまいさを避けるために、クラスのフィールドの先頭には *this* キーワードが付きます。

_disp()_は単純な関数定義です。 ここではfunctionキーワードは使用されないことに注意してください。

コンパイル時に、次のJavaScriptコードが生成されます。

//Generated by typescript 1.8.10
var Car = (function () {
  //constructor
   function Car(engine) {
      this.engine = engine;
   }

  //function
   Car.prototype.disp = function () {
      console.log("Engine is  :   " + this.engine);
   };
   return Car;
}());

インスタンスオブジェクトの作成

クラスのインスタンスを作成するには、 new キーワードにクラス名を続けて使用します。 同じための構文は以下のとおりです-

構文

var object_name = new class_name([ arguments ])
  • new キーワードはインスタンス化を担当します。
  • 式の右側は、コンストラクターを呼び出します。 パラメーター化されている場合、コンストラクターに値を渡す必要があります。

例:クラスのインスタンス化

var obj = new Car("Engine 1")

属性と機能へのアクセス

クラスの属性と機能は、オブジェクトを介してアクセスできます。 使用 ' 。 」クラスのデータメンバーにアクセスするためのドット表記(ピリオドと呼ばれる)。

//accessing an attribute
obj.field_name

//accessing a function
obj.function_name()

例:それらをまとめる

class Car {
  //field
   engine:string;

  //constructor
   constructor(engine:string) {
      this.engine = engine
   }

  //function
   disp():void {
      console.log("Function displays Engine is  :   "+this.engine)
   }
}

//create an object
var obj = new Car("XXSY1")

//access the field
console.log("Reading attribute value Engine as :  "+obj.engine)

//access the function
obj.disp()

コンパイル時に、次のJavaScriptコードが生成されます。

//Generated by typescript 1.8.10
var Car = (function () {
  //constructor
   function Car(engine) {
      this.engine = engine;
   }

  //function
   Car.prototype.disp = function () {
      console.log("Function displays Engine is  :   " + this.engine);
   };
   return Car;
}());

//create an object
var obj = new Car("XXSY1");

//access the field
console.log("Reading attribute value Engine as :  " + obj.engine);

//access the function
obj.disp();

上記のコードの出力は次のとおりです-

Reading attribute value Engine as :  XXSY1
Function displays Engine is  :   XXSY1

クラスの継承

TypeScriptは、継承の概念をサポートしています。 継承とは、既存のクラスから新しいクラスを作成するプログラムの機能です。 新しいクラスを作成するために拡張されたクラスは、親クラス/スーパークラスと呼ばれます。 新しく作成されたクラスは、子/サブクラスと呼ばれます。

クラスは、「extends」キーワードを使用して別のクラスから継承します。 子クラスは、親クラスのプライベートメンバーとコンストラクターを除くすべてのプロパティとメソッドを継承します。

構文

class child_class_name extends parent_class_name

ただし、TypeScriptは多重継承をサポートしていません。

例:クラスの継承

class Shape {
   Area:number

   constructor(a:number) {
      this.Area = a
   }
}

class Circle extends Shape {
   disp():void {
      console.log("Area of the circle:  "+this.Area)
   }
}

var obj = new Circle(223);
obj.disp()

コンパイル時に、次のJavaScriptコードが生成されます。

//Generated by typescript 1.8.10
var __extends = (this && this.__extends) || function (d, b) {
   for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
   function __() { this.constructor = d; }
   d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Shape = (function () {
   function Shape(a) {
      this.Area = a;
   }
   return Shape;
}());

var Circle = (function (_super) {
   __extends(Circle, _super);
   function Circle() {
      _super.apply(this, arguments);
   }

   Circle.prototype.disp = function () {
      console.log("Area of the circle:  " + this.Area);
   };
   return Circle;
}(Shape));

var obj = new Circle(223);
obj.disp();

上記のコードの出力は次のとおりです-

Area of the Circle: 223

上記の例では、クラスShapeを宣言しています。 クラスはCircleクラスによって拡張されます。 クラス間に継承関係があるため、子クラス、つまり クラスCarは、その親クラス属性への暗黙的なアクセスを取得します。 エリア。

継承は次のように分類できます-

  • シングル-すべてのクラスは、最大で1つの親クラスから拡張できます。
  • Multiple -クラスは複数のクラスから継承できます。 TypeScriptは多重継承をサポートしていません。
  • マルチレベル-次の例は、マルチレベル継承の仕組みを示しています。

class Root {
   str:string;
}

class Child extends Root {}
class Leaf extends Child {}//indirectly inherits from Root by virtue of inheritance

var obj = new Leaf();
obj.str ="hello"
console.log(obj.str)

クラスLeafは、マルチレベルの継承により、RootクラスとChildクラスから属性を派生します。

コンパイル時に、次のJavaScriptコードが生成されます。

//Generated by typescript 1.8.10
var __extends = (this && this.__extends) || function (d, b) {
   for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
   function __() { this.constructor = d; }
   d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};

var Root = (function () {
   function Root() {
   }
   return Root;
}());

var Child = (function (_super) {
   __extends(Child, _super);
   function Child() {
      _super.apply(this, arguments);
   }
   return Child;
}(Root));

var Leaf = (function (_super) {
   __extends(Leaf, _super);
   function Leaf() {
      _super.apply(this, arguments);
   }
   return Leaf;
}(Child));

var obj = new Leaf();
obj.str = "hello";
console.log(obj.str);

その出力は次のとおりです-

出力

hello

TypeScript─クラスの継承とメソッドのオーバーライド

メソッドのオーバーライドは、子クラスがスーパークラスのメソッドを再定義するメカニズムです。 次の例は同じことを示しています-

class PrinterClass {
   doPrint():void {
      console.log("doPrint() from Parent called…")
   }
}

class StringPrinter extends PrinterClass {
   doPrint():void {
      super.doPrint()
      console.log("doPrint() is printing a string…")
   }
}

var obj = new StringPrinter()
obj.doPrint()

superキーワードは、クラスの直接の親を参照するために使用されます。 キーワードを使用して、変数、プロパティ、またはメソッドのスーパークラスバージョンを参照できます。 行13は、doWork()関数のスーパークラスバージョンを呼び出します。

コンパイル時に、次のJavaScriptコードが生成されます。

//Generated by typescript 1.8.10
var __extends = (this && this.__extends) || function (d, b) {
   for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
   function __() { this.constructor = d; }
   d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};

var PrinterClass = (function () {
   function PrinterClass() {
   }
   PrinterClass.prototype.doPrint = function () {
      console.log("doPrint() from Parent called…");
   };
   return PrinterClass;
}());

var StringPrinter = (function (_super) {
   __extends(StringPrinter, _super);

   function StringPrinter() {
      _super.apply(this, arguments);
   }

   StringPrinter.prototype.doPrint = function () {
      _super.prototype.doPrint.call(this);
      console.log("doPrint() is printing a string…");
   };

   return StringPrinter;
}(PrinterClass));

var obj = new StringPrinter();
obj.doPrint();

上記のコードの出力は次のとおりです-

doPrint() from Parent called…
doPrint() is printing a string…

静的キーワード

staticキーワードは、クラスのデータメンバーに適用できます。 静的変数は、プログラムが実行を終了するまでその値を保持します。 静的メンバーはクラス名によって参照されます。

class StaticMem {
   static num:number;

   static disp():void {
      console.log("The value of num is"+ StaticMem.num)
   }
}

StaticMem.num = 12    //initialize the static variable
StaticMem.disp()     //invoke the static method

コンパイル時に、次のJavaScriptコードが生成されます。

//Generated by typescript 1.8.10
var StaticMem = (function () {
   function StaticMem() {
   }

   StaticMem.disp = function () {
      console.log("The value of num is" + StaticMem.num);
   };

   return StaticMem;
}());

StaticMem.num = 12;    //initialize the static variable
StaticMem.disp();     //invoke the static method

上記のコードの出力は次のとおりです-

The value of num is 12

instanceof演算子

オブジェクトが指定されたタイプに属する場合、 instanceof 演算子はtrueを返します。

class Person{ }
var obj = new Person()
var isPerson = obj instanceof Person;
console.log(" obj is an instance of Person " + isPerson);

コンパイル時に、次のJavaScriptコードが生成されます。

//Generated by typescript 1.8.10
var Person = (function () {
   function Person() {
   }
   return Person;
}());

var obj = new Person();
var isPerson = obj instanceof Person;
console.log(" obj is an instance of Person " + isPerson);

上記のコードの出力は次のとおりです-

obj is an instance of Person True

データ隠蔽

クラスは、他のクラスのメンバーに対するデータメンバーの可視性を制御できます。 この機能は、データの非表示またはカプセル化と呼ばれます。

オブジェクト指向では、アクセス修飾子またはアクセス指定子の概念を使用して、カプセル化の概念を実装します。 アクセス指定子/変更子は、その定義クラス外のクラスのデータメンバーの可視性を定義します。

TypeScriptでサポートされているアクセス修飾子は-

S.No. Access Specifier & Description
1.

public

パブリックデータメンバーは、ユニバーサルアクセシビリティを備えています。 クラスのデータメンバーはデフォルトでパブリックです。

2.

private

プライベートデータメンバーは、これらのメンバーを定義するクラス内でのみアクセスできます。 外部クラスメンバーがプライベートメンバーにアクセスしようとすると、コンパイラはエラーをスローします。

3.

protected

保護されたデータメンバーは、前のクラスと同じクラス内のメンバー、および子クラスのメンバーからアクセスできます。

次に、データの非表示がどのように機能するかを確認するための例を見てみましょう-

class Encapsulate {
   str:string = "hello"
   private str2:string = "world"
}

var obj = new Encapsulate()
console.log(obj.str)    //accessible
console.log(obj.str2)  //compilation Error as str2 is private

このクラスには、それぞれstr1とstr2の2つの文字列属性があり、それぞれパブリックメンバーとプライベートメンバーです。 クラスがインスタンス化されます。 この例は、プライベート属性str2がそれを宣言するクラスの外部からアクセスされるため、コンパイル時エラーを返します。

クラスとインターフェース

クラスはインターフェイスも実装できます。

interface ILoan {
   interest:number
}

class AgriLoan implements ILoan {
   interest:number
   rebate:number

   constructor(interest:number,rebate:number) {
      this.interest = interest
      this.rebate = rebate
   }
}

var obj = new AgriLoan(10,1)
console.log("Interest is : "+obj.interest+" Rebate is : "+obj.rebate )

クラスAgriLoanは、インターフェイスLoanを実装します。 したがって、クラスにバインドして、プロパティ interest をそのメンバーとして含めるようになりました。

コンパイル時に、次のJavaScriptコードが生成されます。

//Generated by typescript 1.8.10
var AgriLoan = (function () {
   function AgriLoan(interest, rebate) {
      this.interest = interest;
      this.rebate = rebate;
   }
   return AgriLoan;
}());

var obj = new AgriLoan(10, 1);
console.log("Interest is : " + obj.interest + " Rebate is : " + obj.rebate);

上記のコードの出力は次のとおりです-

Interest is : 10 Rebate is : 1