JavaScript는 prototype 기반의 언어이다. JavaScript는 상속이 없으나 최근 class 도입에 따라 가능하게 되었다. 그러나 prototype을 활용한 상속의 구현이 여전히 더 많이 사용된다.
function School(address) {
this.name = "Seneca";
this.address = address;
}
var mySchool = new School("Finch");
console.log(mySchool.name); // Seneca
console.log(mySchool.address); // Finch
What if 객체가 10개 100개 그 이상 생성된다면, 메모리가 갖게되는 수도 그만큼 늘어날 것이다. 이를 prototype을 통한 접근으로 상속을 통해 해결한다.
/* 함수를 선언하게 되면 (1)생성자 기능부여, (2)prototype object 생성이 일어난다 */
function School(){}
// (1)생성자 기능 - 함수만 가능
var mySchool = new School();
// (2) prototype object 생성
/* 함수가 생성되면서 prototype object가 생성된다. */
/* 함수는 prototype 프러퍼티를 통해 prototype object에 접근한다. */
School.prototype.name = "Seneca";
/* prototype object는 디폴트로 constructor()와 __proto__ 를 갖는다.(prototype link 라함) */
/* prototype 프러퍼티를 통해 prototype object에 속성을 추가할수 있다. */
/* 객체를 생성하게 되면, 생성된 객체는 __proto__ 를 갖는다. */
var mySchool = new School();
/* mySchool 의 __proto__ 는 School의 prototype object 를 가리키며, 이를 통해 데이터를 찾게된다. */
/* 마찬가지로 School 의 __proto__ 도 상위 prototype object (Object())를 탐색하게된다. */
/* 이렇게 상위 prototype으로 연결된걸 prototype chain 이라 한다. */
prototype 관계도
Simple 예제
function School(address) {
// 객체 생성시 추가
this.address = address;
}
// 상속받아서 사용
School.prototype.name = "Seneca";
var mySchool = new School("Finch");
console.log(mySchool.name);
console.log(mySchool.address);
var yourSchool = new School("York");
console.log(yourSchool.name);
console.log(yourSchool.address);
'JavaScript' 카테고리의 다른 글
Template Literals (0) | 2020.12.03 |
---|---|
정규식 (0) | 2020.12.03 |
즉시 실행 함수(IIFE: Immediately Invoked Function Expression) (0) | 2020.12.02 |
Callback, Promise, Observable and Async/await (0) | 2020.12.02 |
this 키워드 (this, call, apply, bind and arrow function) (0) | 2020.12.01 |