function Constructor1(){
this.name = "bora"; // 여기서의 this는 새로 만들어지는 객체를 뜻하게됨 = **instance**
this.age = 30;
}
const user1 = new Constructor1();
// Constructor1 {name: "bora", age: 30}
function Constructor2(name, age){
this.name = name;
this.age = age;
}
const user2 = new Constructor2("ddubie", 1);
// Constructor2 {name: "ddubie", age: 1}
function Constructor2(name, age){
this.name = name;
this.age = age;
}
Constructor2.prototype.gender = "male" // prototype 추가
const user2 = new Constructor2("ddubie", 1);
// Constructor2 {name: "ddubie", age: 1} →→ 객체 자체가 바뀌는건 아니다
console.log(user2.gender);
// male →→ prototype에 추가한 값을 자식요소에서 꺼낼 수 있음
const arr = [1,2,3]
arr.sort();
// 별도의 함수를 만든적이 없는데 함수를 사용할 수 있다.
실행순서)
1. arr에서 sort라는 함수를 가지고있는가? → X
2. 그 부모요소의 prototype에 sort라는 함수를 가지고있는가? → O
why? arr를 새로 만든다는건 자바스크립트의 Array라는 constructor를 통해 만들어진다는 의미
const arr = [1,2,3]
는 어떤 동작이냐면,
const arr = new Array(1,2,3)
이렇게 자바스크립트가 갖고있는 constructor를 통해 만들어낸 array인 것!
그렇기 때문에 부모요소인 Array라는 constructor에서 prototype에 갖고있는 다양한 내장함수들을 자연스럽게 사용할 수 있는 것이다!!
__proto__arr.__proto__;
__proto__로 강제 부모-자식관계 등록할 수 있음const parents = { name : "bora" };
const child = {};
child.__proto__ = parents;
console.log(child.name);
// 'bora'
__proto__항목 확인)let a = { name : "bora" }
let b = Object.create(a)
// ↑ b의 prototype을 a로 해주세요 라는 뜻이됨
=> b(자식)에서 a(부모)를 상속받게됨
위 상황을 콘솔로 찍어보면 어떻게나올까?
console.log(b)
→ {}
// 왜?? b를 직접적으로 정의해준적이 없기 때문에 비어있는것이 당연!
console.log(b.name)
→ "bora"
// 왜?? 가장먼저 b에서 name을 갖고있는지 확인 후, 없으면 부모 prototype에 name이 있는지 확인해서 출력해주기때문.