aspe

Javascript - Prototype 본문

카테고리 없음

Javascript - Prototype

aspe 2021. 12. 4. 18:22

Prototype

Javascript는 모든 객체들이 메소드와 속성들을 상속 받기 위한 템플릿으로써 prototype object를 갖는 prototype-based language라 불린다. 

간단하게 설명하면 상속 받는 것들은 prototype에 담아서 prototype chain을 이용하여 사용 할 수 있게끔 한다.

function Person(first, last, age, gender, interests) {

  // 속성과 메소드 정의
  this.first = first;
  this.last = last;
//...
}
var person1 = new Person('Bob', 'Smith', 32, 'male', ['music', 'skiing']);

위의 코드에서 최상위 객체인 Object에 있으면서 person1이 상속받은 메소드(예를들면 valueOf())를 사용하려고 한다. 

1. 우선 person1이 valueOf() 메소드를 갖고 있는지 확인한다. 없다면 다음단계

2.  person1의 prototype object(Person()의 constructor's prototype, Person.prototype)을 확인한다. 없다면 다음단계

3. Person() constructor의 prototype object의 protytpe object(Object() constructor의 prototype)가 valueOf()

중요한 것은 Object의 메소드를 복사하여 person1에게 상속하는 것이 아니라 chain을 타고 올라간다는 것이다.
그래서 prototype 버킷에 정의되지 않는 멤버들은 상위 객체의 생성자에서만 사용할 수 있다.

프로토타입 객체는 __proto__ 속성으로(상속 받은 쪽에서) 접근 가능한 내장 객체이다.

그래서 Person.prototype과 person1.__proto__는 같은 것을 알 수 있다.

 

create() 예시

var person2 = Object.create(person1);
person2.__proto__

이것을 실행하면 person1이 출력된다.

그 이유는 create() 메소드가 실제로 하는 일이 주어진 객체(person1)를 prototype object로 삼아 새로운 object를 생성하는 것이기 때문이다.

생성자 속성

모든 생성자 함수는 constructor 속성을 지닌 object를 prototype object로 가지고 있다.

이 constructor 속성은 원본 생성자 함수 자신을 가리키고 있으며 Person.prototype 속성에 정의된 속성들은 Person() 생성자로 생성된 모든 인스턴스에서 사용할 수 있다.(위에서 말했던 그대로다 Person,prototype은 상속해주는 버킷이니까 Person() 생성자로 생성된 인스턴스(person1)은 Person.prototype 속성에 정의된 모든 인스턴스를 사용할 수 있는 것이다.)

 

프로토타입 수정하기

Person.prototype.farewell = function() {
  alert(this.name.first + ' has left the building. Bye for now!');
};
person1.farewell();

위의 코드를 실행하면 잘 동작하는 것을 알 수 있다. 그리고 Person.prototype에는 farewell이라는 메소드가 추가된다.

참조 https://developer.mozilla.org/ko/docs/Learn/JavaScript/Objects/Object_prototypes

 

Comments