[JavaScript] Prototype Chain
13142 ワード
Prototype
JavaScriptのすべてのオブジェクトは、親として機能するオブジェクトに関連付けられています.また、これは、親オブジェクトのプロパティまたはメソッドを継承および使用できるようにするオブジェクト向けの継承概念のようなものです.これらの親は、
Prototype(프로토타입) 객체
またはPrototype(프로토타입)
と呼ばれる.Prototype 객체
は、コンストラクション関数によって生成された各オブジェクトに対して共有属性を提供するために使用される.要するに、簡単に説明すると、モデル青写真を作成する際に使用するプロトタイプオブジェクトです.
コンストラクタ
Prototype
オブジェクトはconstructor property
を有する.このconstructor property
とは、オブジェクトの角度から自分のオブジェクトを作成することを意味する.例えば、
Person()
生成器関数によって生成されるオブジェクトをfoo
と呼ぶ.このfoo
オブジェクトを生成するオブジェクトは、Person()
ジェネレータ関数です.このとき、foo
オブジェクトについては、自身を生成するオブジェクトがPerson()
ジェネレータ関数であり、foo
オブジェクトのPrototype
オブジェクトがPerson.prototype
である.したがって、Prototype
オブジェクトPerson.prototype
のconstructor property
は、Person()
構造関数を指す.function Person(name) {
this.name = name;
}
var foo = new Person('Lee');
// Person() 생성자 함수에 의해 생성된 객체를 생성한 객체는 Person() 생성자 함수이다.
console.log(Person.prototype.constructor === Person);
👉 true
// foo 객체를 생성한 객체는 Person() 생성자 함수이다.
console.log(foo.constructor === Person);
👉 true
// Person() 생성자 함수를 생성한 객체는 Function() 생성자 함수이다.
console.log(Person.constructor === Function);
👉 true
Prototype Chain
オブジェクトのプロパティまたはメソッドにアクセスする場合、JavaScriptは、オブジェクト自体および
__proto__
が指すリンクを介して、親オブジェクトとしてのプロトタイプまたはメソッドにアクセスできます.すなわち、あるオブジェクトのpropertyまたはメソッドにアクセスする際に、現在のオブジェクトのpropertyが存在しない場合、
__proto__
が指すリンクに従って親としてのprototypeオブジェクトのpropertyまたはメソッドがprototypeチェーンであることを順次検索する.Example
💻 Code
const car = {
wheels: 4,
drive(){
console.log("drive...");
},
};
const bmw = {
color: "red",
navigation: 1,
};
bmw.__proto__=car;
const x5 = {
color: "white",
name: "x5",
};
x5.__proto__=bmw;
✔ Resultx5.name
👉 "x5"
x5.color
👉 "white"
x5.navigation
👉 1
x5.drive();
👉 drive...
注意事項x5
👉 {color: "white", name: "x5"}
for(let p in x5){
console.log(p);
}
👉 color
👉 name
👉 navigation
👉 wheels
👉 drive
// color와 name을 제외한 나머지들은 Prototpye에서 정의한 property이다.
for(p in x5){
if(x5.hasOwnProperty(p)){
console.log('o', p);
} else{
console.log('x', p);
}
}
👉 o color
👉 o name
👉 x navigation
👉 x wheels
👉 x drive
Object.keys(x5);
(2) ["color", "name"]
Object.values(x5);
(2) ["white", "x5"]
💻 コンストラクション関数の使用const Bmw = function (color){
this.color = color;
};
Bmw.prototype = {
constructor: Bmw,
// 명시하지 않을 경우 z4.constructor === Bmw; 는 false값이 나온다
// 이런 현상을 방지하기 위해 Prototype으로 덮어씌우지 않고 하나씩 property를 추가하는 것이 좋다
wheels: 4,
drive() {
console.log("drive...");
},
navigation: 1,
stop() {
console.log("STOP!");
},
};
const z4 = new Bmw("blue");
z4.stop();
👉 STOP!
z4 instanceof Bmw
👉 true
z4.constructor === Bmw;
👉 true
Reference
この問題について([JavaScript] Prototype Chain), 我々は、より多くの情報をここで見つけました https://velog.io/@j_jhwww/TILJavaScript-Prototype-Chainテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol