JavaScript のプロトタイプ デザイン パターンは、オブジェクトを最初から作成するのではなく、既存のオブジェクト (「プロトタイプ」) を複製することによって新しいオブジェクトを作成できるようにする作成パターンです。プロトタイプ。このパターンは、JavaScript 自体がプロトタイプベースの言語であるため、JavaScript に特に適しており、オブジェクトの作成にコストがかかる場合や、基本プロトタイプと特定のプロパティを共有するオブジェクトを作成したい場合に役立ちます。
ES6 クラスを使用すると、オブジェクトの構造を理解しやすくなります。 extends を使用すると継承が簡素化されますが、ES6 より前では、これを継承して実装するためにプロトタイプが使用されていました。この概念を理解するためのブログは次のとおりです。
追伸: JavaScript のプロトタイプ設計パターンには、他の言語 (Java など) にあるような組み込み clone() メソッドはありません。ただし、プロトタイプまたはコンストラクター関数に clone() メソッドを手動で実装して、同様の機能を提供することができます。
プロトタイプ パターンの背後にある考え方は次のとおりです:
プロトタイプ: 新しいオブジェクトの作成元となるテンプレート オブジェクト。
クローン作成: プロトタイプをコピーすることで新しいオブジェクトが作成されます。
プロトタイプ チェーン: オブジェクトは動作をプロトタイプに委任できます
class Shape { constructor(type = 'Generic Shape', color = 'White') { this.type = type; this.color = color; } getDetails() { return `Type: ${this.type}, Color: ${this.color}`; } // Clone method to create a new object with the same prototype clone() { return Object.create(this); // Creates a new object that inherits from this prototype } }
説明:
目的: Shape クラスは、円や四角形などの特定の形状を継承できる基本クラスまたは「プロトタイプ」として機能します。
clone() メソッド: これはプロトタイプ パターンの重要な部分です。クラスの新しいインスタンスを最初から作成するのではなく、既存のインスタンス (または「プロトタイプ」) のクローンを作成します。この場合、Object.create(this) は、元の Shape.
と同じプロトタイプを共有する新しいオブジェクトを作成します。class Circle extends Shape { constructor(radius = 0, color = 'White') { super('Circle', color); // Calls the parent (Shape) constructor this.radius = radius; } getArea() { return Math.PI * this.radius * this.radius; } }
説明:
目的: Circle クラスは Shape クラスを拡張し、特定の種類の形状を表します。
属性:
getArea() メソッド: これは、式 π * radius^2 を使用して円の面積を計算します。
class Rectangle extends Shape { constructor(width = 0, height = 0, color = 'White') { super('Rectangle', color); // Calls the parent (Shape) constructor this.width = width; this.height = height; } getArea() { return this.width * this.height; } }
説明:
目的: Rectangle クラスは Shape クラスを拡張し、別の特定の種類の形状 (長方形) を表します。
const circlePrototype = new Circle(); // Create prototype const myCircle = circlePrototype.clone(); // Clone the prototype myCircle.radius = 5; myCircle.color = 'Red'; const rectanglePrototype = new Rectangle(); // Create prototype const myRectangle = rectanglePrototype.clone(); // Clone the prototype myRectangle.width = 10; myRectangle.height = 5; myRectangle.color = 'Blue';
説明:
ここでは、new キーワードを使用して myCircle オブジェクトと myRectangle オブジェクトを最初から作成するのではなく、プロトタイプのクローンを作成しています。
クローン作成プロセス:
クローンインスタンスの変更:
console.log(myCircle.getDetails()); // Output: Type: Circle, Color: Red console.log(`Circle Area: ${myCircle.getArea()}`); // Output: Circle Area: 78.54 console.log(myRectangle.getDetails()); // Output: Type: Rectangle, Color: Blue console.log(`Rectangle Area: ${myRectangle.getArea()}`); // Output: Rectangle Area: 50
説明:
プロトタイプ パターンは次の場合に役立ちます:
ここまで進んだ方は?✨、ご質問やご意見があれば、以下にコメントを残してください。ぜひご意見を伺い、素晴らしいディスカッションをしていきたいと思っています!✨
免責事項: 提供されるすべてのリソースの一部はインターネットからのものです。お客様の著作権またはその他の権利および利益の侵害がある場合は、詳細な理由を説明し、著作権または権利および利益の証拠を提出して、電子メール [email protected] に送信してください。 できるだけ早く対応させていただきます。
Copyright© 2022 湘ICP备2022001581号-3