객체 prototype, constructor, 상속(extends)

김승우·2020년 9월 1일
0

TIL

목록 보기
11/68

1. 생성자(Constructor) 함수 : 객체를 생성, 생성자 함수 그 자체


2. Prototype(원형) : 생성자 함수에 정의된, 생성된 객체들이 공유할 원형


3. proto : 객체가 생성될 때(new로 호출할 때) prototype를 참조하여 자동으로 생성된다. 따라서 prototype과 proto는 같다.


4. Extends(상속) : 부모 생성자의 기능을 물려받으면서, 기능을 확장하는 것을 말한다.

  • 코드
//상속할 개체 Person
const Person = function(name,age){
	this.name = name;
    	this.age = age;
}

//Person의 prototype에 'greeting' 메소드 추가
Person.prototype.greeting = function(){
	console.log(this.name, this.age);
}

//상속 받을 객체 Teacher
const Teacher = function(name,age,role){
	Person.apply(this, arguments);
	this.role = role;
}
  1. Person.apply(this, arguments) : Person의 생성자에 Teacher의 this와 arguments를 적용, new 키워드가 없으므로 객체를 생성하지않고, 생성자 함수만 실행되어서 Teacher안에 name, age속성을 추가한다.
  2. this.role = role : role은 Person의 매개변수안에 포함되어있지 않으므로, 따로 속성을 추가.
  3. 현재 Teacher.prototype.constructor === Teacher //true
  4. Teacher에서 Person의 greeting 메소드를 사용하지 못함

5. Object.create(Obj.prototype)과 new Obj()의 차이

: Object.create는 객체를 만들되 생성자는 실행 X, new는 생성자를 실행
: 상속받는 객체의 prototype과 부모의 prototype를 연결시켜준다 => 그래야지 상속받은 객체에서 부모의 메소드를 사용할 수 있다.

Teacher.prototype = Object.create(Person.prototype);
  1. 따라서, greeting 메소드를 사용하기 위해, Teacher의 prototype에 Person의 Prototype를 연결한다.

6. Child.prototype.constructor = Child;

: 생성자.prototype.constructor === 생성자 이므로, 상속받은 객체에서 Child.prototype.constructor = Child를 넣어줘서 에러를 해결해 줘야한다.
: 하지 않았을 경우, Child.prototype.constructor === Parent 상태이다.


profile
사람들에게 좋은 경험을 선사하고 싶은 주니어 프론트엔드 개발자

0개의 댓글