[JavaScript] 객체지향 프로그래밍 3. 프로토타입

Hyun Jin·2023년 1월 13일
0

JavaScript

목록 보기
17/20

Chapter 2. 프로토타입

Chapter 2-1. 프로토타입과 클래스

JavaScript의 모든 객체에는 프로토타입 이라는 내장 속성이 있습니다. 프로토타입은 그 자체로 객체이므로 프로토타입은 자체 프로토타입을 갖게 되어 프로토타입 체인 이라고 불리는 것을 만듭니다 . null자체 프로토타입 이 있는 프로토타입에 도달하면 체인이 종료됩니다 .
개체의 속성에 액세스하려고 할 때 개체 자체에서 속성을 찾을 수 없는 경우 프로토타입에서 속성을 검색합니다. 여전히 속성을 찾을 수 없으면 프로토타입의 프로토타입을 검색하고 속성을 찾거나 체인의 끝에 도달할 때까지 계속 검색합니다. 이 경우 undefined가 반환됩니다.

  • 개체의 프로토타입에 액세스하는 표준 방법 : Object.getPrototypeOf() 메서드
  • Object.prototype.__proto__ (⇒ 더이상 권장되지 않음, but 자주 사용하지 않고 __proto__ 가 더 쓰기 간편하기 때문에, 아예 기능이 삭제되거나 회사에서 사용을 권장하지 않을 때에 Object.getPrototypeOf() 를 쓰면 됨)

For better support, prefer Object.getPrototypeOf(), Reflect.getPrototypeOf() and Object.setPrototypeOf()/Reflect.setPrototypeOf() instead.

그 외 프로토타입 메서드 : constructor, hasOwnProperty, isPrototypeOf, valueOf, _defineGetter, …


Chapter 2-2. 프로토타입 체인

프로토타입 체인 : prototype의 메소드나 변수에 접근하는 것

  • 객체 지향 프로그래밍의 특성 중 상속을 JavaScript에서 구현할 때에는 프로토타입 체인을 사용함.
  • 속성과 메서드를 물려주는 클래스를 부모 클래스, 속성과 메서드를 물려받는 클래스를 자식 클래스, 그리고 이 과정을 상속이라고 함.
  • 자바스크립트에서는 class, extends 와 super 키워드를 이용해서 상속을 구현할 수 있음.(클래스도 프로토타입 기반)
    상속 구현방법 중 클래스 MDN 페이지 참조

1. 프로토타입 체인 접근 방법

외부에서 직접 접근은 불가능함.
1. __proto__
2. Object.getPrototypeOf()
3. Object.setPrototypeOf()
생성자 함수에서는 prototype 으로 접근 가능.

+)

2. 프로토타입의 상속 방법

  1. new 생성자 함수 사용

  2. Object.create()

    예시

    Dog.prototype = Object.create(Animal.prototype)
    function Dog(name, emoji, owner){
    Animal.call(this, name,emoji){
    this.owner = owner;
  3. mixin(Object.assign(Dog.prototype, 프로토타입을 할당한 변수 1, 프로토타입 변수2)) : 여러개의 프로토타입을 상속할 때 쓰임.

  4. 최신 방법은 클래스(class, extends, super)!!

DOM과 프로토타입

📚 추가 학습

🔸Object.prototype.hasOwnProperty()
Return value : Returns true if the object has the specified property as own property; false otherwise.
The hasOwnProperty() method returns true if the specified property is a direct property of the object — even if the value is null or undefined. The method returns false if the property is inherited, or has not been declared at all. Unlike the in operator, this method does not check for the specified property in the object's prototype chain.

🔗 참고 사이트 : MDN

profile
새싹 프론트엔드 개발자

0개의 댓글