JavaScriptの多形
6096 ワード
多形はオブジェクト指向プログラミングからの概念である.複数の実装を持つプロパティ、関数、またはオブジェクトを作成する機能です.
共通の機能を持つクラスでプロパティやメソッドを置き換えることができます.メソッドのオーバーライドに似ています.多型性では、標準インターフェイスを実装することができますが、まだわずかに異なるニーズやシナリオを提供します.
私たちはクラスと同じことができます.
共通の機能を持つクラスでプロパティやメソッドを置き換えることができます.メソッドのオーバーライドに似ています.多型性では、標準インターフェイスを実装することができますが、まだわずかに異なるニーズやシナリオを提供します.
function Employee(name) {
this.name = name;
this.getName = () => {
return this.name;
}
}
const employee = new Employee("Parwinder");
console.log(employee.getName()); // Parwinder
Employee.prototype.getDetails = function () {
return this.name.toUpperCase();
}
console.log(employee.getDetails()); // PARWINDER
あなたはどのようにEmployee
は標準インターフェースを実装するが、Employee
我々はわずかに我々のニーズに合うように行動を変更することができます.私たちは名前を得るか、すべての大文字で名前を得ることができました.私たちはクラスと同じことができます.
class Shape {
area() {
return 0;
}
}
class Circle extends Shape {
constructor (radius) {
super(); // needed to use this
this.radius = radius;
}
area() {
return Math.PI * this.radius * this.radius;
}
}
class Rectangle extends Shape {
constructor (width, height) {
super();
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
const circle = new Circle(2);
const rectangle = new Rectangle(5, 6);
console.log(circle.area());
console.log(rectangle.area());
Shape
作成する基底クラスですCircle
and Rectangle
拡張することで.彼らはみなarea
しかし、型の型に基づいて実装を変更します.Reference
この問題について(JavaScriptの多形), 我々は、より多くの情報をここで見つけました https://dev.to/bhagatparwinder/polymorphism-in-javascript-1960テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol