JavaScript_Study [ Prototype (프로토타입 객체) ]

이준석·2023년 4월 4일
0

JavaScript_Study

목록 보기
9/35
post-thumbnail

2021-08-30 노션페이지,
2021-09-12 노션페이지,
2021-09-13 노션페이지
기록된 노션을 다시 정리

어려웠던 부분

  • 비슷 단어들과 상속 관계 및 가르키는 객체
    • proto 프로퍼티
    • [[Prototype]] vs prototype 프로퍼티
    • 아래 정리 확인

prototype

자바스크립트의 모든 객체는 자신의 부모 역할을 담당하는 객체와 연결되어 있다.
부모 객체를 Prototype(프로토타입) 객체 또는 줄여서 Prototype(프로토타입)이라 한다.

  • prototype을 사용하는 객체끼리 부모와 자식의 형태를 가짐
  • 자식은 부모의 속성 사용가능 (부모는 자식의 속성 사용 불가능)
  • 모든 객체의 프로토타입 객체인 Object.prototype 객체

1. __proto__ 프로퍼티

__proto__ 프로퍼티에 접근하면 내부적으로 Object.getPrototypeOf가 호출되어 프로토타입 객체를 반환한다.
=> __proto__을 호출하면 자신의 prototype객체를 반환한다.

// student 객체는 __proto__ 프로퍼티로 자신의 부모 객체(프로토타입 객체)인 Object.prototype을 가리키고 있다.
var student = {
  name: 'Lee',
  score: 90
}
// student는 Object의 prototype객체를 상속 받고있다.
console.log(student.__proto__ === Object.prototype); // true

2. [[Prototype]] vs prototype 프로퍼티

function Person(name) {
  this.name = name;
}
var foo = new Person('Lee');
  • [[Prototype]]
    - 객체의 입장에서 자신의 부모 역할을 하는 프로토타입 객체를 가리키며 함수 객체의 경우 Function.prototype를 가리킨다.
    console.log(Person.__proto__ === Function.prototype);
  • prototype 프로퍼티
    - 함수 객체만 가지고 있는 프로퍼티이다.
    - 함수 객체가 생성자로 사용될 때 이 함수를 통해 생성될 객체의 부모 역할을 하는 객체(프로토타입 객체)를 가리킨다. (인스터스의 부모 => 생성자 함수)
    console.log(Person.prototype === foo.__proto__);

3. constructor 프로퍼티

프로토타입 객체는 constructor 프로퍼티를 갖는다.
이 constructor 프로퍼티는 객체의 입장에서 자신을 생성한 객체를 가리킨다.

function Person(name) {
  this.name = name;
}

var foo = new Person('Lee');

// Person() 생성자 함수에 의해 생성된 객체를 생성한 객체는 Person() 생성자 함수이다.
// Person의 prototype객체를 만든 게 누구인지
console.log(Person.prototype.constructor === Person);

// foo 객체를 생성한 객체는 Person() 생성자 함수이다.
console.log(foo.constructor === Person);

// Person() 생성자 함수를 생성한 객체는 Function() 생성자 함수이다.
console.log(Person.constructor === Function);

4. Prototype chain

자바스크립트는 특정 객체의 프로퍼티나 메소드에 접근하려고 할 때 해당 객체에 접근하려는 프로퍼티 또는 메소드가 없다면 [[Prototype]]이 가리키는 링크를 따라 자신의 부모 역할을 하는 프로토타입 객체의 프로퍼티나 메소드를 차례대로 검색한다. 이것을 프로토타입 체인이라 한다.
!! Object.prototype 객체를 프로토타입 체인의 종점(End of prototype chain)이라 한다.

5. 프로토타입 객체의 확장

프로토타입 객체도 객체이므로 일반 객체와 같이 프로퍼티를 추가/삭제할 수 있다.
그리고 이렇게 추가/삭제된 프로퍼티는 즉시 프로토타입 체인에 반영된다.
ex)

function Person(name) {
  this.name = name;
}

var foo = new Person('Lee');

Person.prototype.sayHello = function(){
  console.log('Hi! my name is ' + this.name);
};

// Person을 prototype으로 가지는 객체들은 sayHello를 사용할 수 있다.
foo.sayHello();

6. 프로토타입 객체의 변경

  • 객체를 생성할 때 프로토타입은 결정된다.
  • 결정된 프로토타입 객체는 다른 임의의 객체로 변경할 수 있다.
    => 부모 객체인 프로토타입을 동적으로 변경할 수 있다는 것을 의미한다.

7. 프로토타입 체인 동작 조건

  • 객체의 프로퍼티를 참조하는 경우,
    프로토타입 체인이 동작한다.
  • 객체의 프로퍼티에 값을 할당하는 경우,
    프로토타입 체인이 동작하지 않는다.

참조: poiemaweb.com

0개의 댓글