[JavaScript] Prototype
プロトタイプベースの言語?
JavaScriptは通常、プロトタイプベースの言語と呼ばれます.
これは、すべてのオブジェクトが継承メソッドと属性のテンプレートとしてプロトタイプオブジェクト(prototype object)を持っていることを意味します.
プロトタイプオブジェクトを理解します。
const x = {};
const y = {};
console.log(x);
console.log(y);
コンソールは、オブジェクトに何も含まれていないxおよびyです.Prototypeを含むログに出力します.PrototypeはObjectとして宣言されます.
つまり、JavaScriptでは、すべてのオブジェクトがPrototypeオブジェクトを継承します.
このように,プロトタイプにはオブジェクトで使用できる基本関数がたくさんあり,これらはすべて使用できる.
(x.toString()、x.toLocaleString()など.)
xとyは同じオブジェクトのプロトコルを継承する.
xのprotoとyのprotoは同じ結果値を有する.
console.log(x.__proto__ === y.__proto__) // true
array
Array変数のオブジェクトはArrayを継承し、このarrayプロトコルはObjectを継承します.
したがってjsのすべてのオブジェクトにはObjectというProtoがあります.
さらに、任意のタイプのオブジェクトを考慮することなく、toStringを無条件に使用します.
Instance member level
function CoffeeMachine(beans) {
this.beans = beans;
this.makeCoffee = shots => {
console.log('making coffee');
};
}
const machine1 = new CoffeeMachine(10);
const machine2 = new CoffeeMachine(20);
console.log(machine1);
console.log(machine2);
Prototype member level
function CoffeeMachine(beans) {
this.beans = beans;
}
// Prototype member level
CoffeeMachine.prototype.makeCoffee = shots => {
console.log('making coffee');
};
const machine1 = new CoffeeMachine(10);
const machine2 = new CoffeeMachine(20);
console.log(machine1);
console.log(machine2);
オブジェクトのmakeCoffeeをプロトコルを開くとmakeCoffeeが共通に変更されます.
Machine 1と2はCoffeeMachineを継承します.
CoffeeMachineはオブジェクトを継承します.
Create
LatteMachineのモデルはObjectです.CoffeeMachineのプロトタイプにcreateを使用して接続します.
LatteMachineはCoffeeMachineを継承し、最終的には
LatteMachineではmakeCoffeeという関数も使用できます.
function LatteMachine(milk) {
this.milk = milk;
}
LatteMachine.prototype = Object.create(CoffeeMachine.prototype);
const latteMachine = new LatteMachine(123);
console.log(latteMachine);
latteMachine.makeCoffee();
の最後の部分
Javascriptでは、タイプスクリプトのようなインタフェースやJENEICはありませんが、プロトタイプを使用して継承を実現できます.
プロトコルタイプは、JavaScriptからオブジェクト向けのプログラミングを継承し、コードを再使用するために使用されます.
Reference
この問題について([JavaScript] Prototype), 我々は、より多くの情報をここで見つけました https://velog.io/@godud2604/JavaScript-Prototypeテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol