クラスとプロトタイプ&プロトタイプチェーン
プロトタイプ
モデルの青写真を作成するプロトタイプオブジェクト(元のフォーム).
関数はオブジェクトです.
したがって、コンストラクション関数もオブジェクトです(propertyを持つことができます).
prototypeは特殊な約束用途のpropertyである.
class Human {
constructor(name, age) {
this.name = name;
this.age = age;
}
sleep() {
console.log(`${this.name}은 잠에 들었습니다`);
}
}
let kimcoding = new Human('김코딩', 30);
// 실습해보세요
Human.prototype.constructor === Human; // true
Human.prototype === kimcoding.__proto__; // true
Human.prototype.sleep === kimcoding.sleep; // true
Human.prototype.sleep === kimcoding.__proto__.sleep;//true



class Human {
constructor(name, age){
this.name = name;
this.age = age;
}
sleep(){ return `${this.name}이(가) 잠을 잡니다.`}
}
// undefined
const steve = new Human('Steve', 20);
// undefined
steve
// Human {name: 'Steve', age: 20}age: 20name: "Steve"[[Prototype]]: Objectconstructor: class Humansleep: ƒ sleep()[[Prototype]]: Object
steve.__proto__ === Human.prototype;
// true
// steve.__proto__의 주소가 Human.prototype의 주소와 같다.
Human.prototype.sleep
// ƒ sleep(){ return `${this.name}이(가) 잠을 잡니다.`}
steve.__proto__.sleep
// ƒ sleep(){ return `${this.name}이(가) 잠을 잡니다.`}
steve.__proto__.sleep()
// 'undefined이(가) 잠을 잡니다.'
steve.sleep()
// 'Steve이(가) 잠을 잡니다.'
Human
// class Human {
// constructor(name, age){
// this.name = name;
// this.age = age;
// }
// sleep(){ return `${this.name}이(가) 잠을 잡니다.`}
// }
console.dir(Human)
// class Humanlength: 2name: "Human"prototype: {constructor: ƒ, sleep: ƒ}arguments: (...)caller: (...)[[FunctionLocation]]: VM97:2[[Prototype]]: ƒ ()[[Scopes]]: Scopes[2]
class blahblah { sleep() { console.log('meh')}}
// undefined
blahblah
// class blahblah { sleep() { console.log('meh')}}
console.dir(blahblah)
// class blahblahlength: 0name: "blahblah"prototype: {constructor: ƒ, sleep: ƒ}arguments: (...)caller: (...)[[FunctionLocation]]: VM1154:1[[Prototype]]: ƒ ()[[Scopes]]: Scopes[2]
steve.__proto__ === Human.prototype;
// true
Human.prototype
// {constructor: ƒ, sleep: ƒ}
Human.prototype.constructor === Human
// true
Human.prototype.constructor === Human;
Human.prototype === steve.__proto__;
Human.prototype.sleep === steve.sleep;

Array.prototype.constructor === Array;
Array.prototype === arr.__proto__;
Array.prototype.push === arr.push;

プロトタイプチェーン
基本タイプから親基本タイプの構造.
つまり、子タイプは親タイプのプロパティとメソッドを共有します.
addEventListenerプロパティはどのクラスのプロトタイプで見つけることができますか?
EventTarget
removeメソッドはどのクラスのプロトタイプで見つけることができますか?
Element
なぜすべてのオブジェクトにtoString()メソッドがあるのですか?
オブジェクトの文字列表現を返します.
通常、toStringメソッドは、オブジェクトが「テキスト」であることを示す文字列を返します.
結果は簡潔で読みやすいが有益な表現であるべきである.このメソッドは、すべてのサブクラスで再定義することを推奨します.
Reference
この問題について(クラスとプロトタイプ&プロトタイプチェーン), 我々は、より多くの情報をここで見つけました https://velog.io/@jelkov/클래스와-프로토타입テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol