230321_TIL

·2023년 3월 21일
0

Prototype

  • TS, JS , JAVA === Class / JS ES5 === Prototype

  • 모든 객체는 내부에 숨겨진 [[Prototype]]을 가지고 있다. (객체간 상속을 위해)

  • 외부에서 직접 접근이 불가하고, 아래 키워드로 접근이 가능하다.

    __proto__ Object.getPrototypeOf() Onject.setPrototypeOf()

    생성자 함수에서는 :prototype으로 접근 가능

  • 배열이나 객체를 임의로 선언하고, .을 찍어보면 사용할 수 있는 메소드들이 나오는데, 해당 메소드들은 자바스크립트 개발자들이 prototype으로 사용할 수 있도록 만든 함수들이다.

요약

객체간 상속의 연결 고리는 프로토타입 체인으로 연결되어 있음.

요약 코드

const dog = { name: "벅이", emoji: "🐶" };
console.log(" Object.keys(dog) : ", Object.keys(dog)); // 객체의 key만 출력
console.log(" Object.values(dog) : ", Object.values(dog)); // 객체의 value만 출력
console.log(" Object.entries(dog) : ", Object.entries(dog)); // 객체의 key와 value를 pair 출력

// 객체에서는 in이라는 연산자를 이용하여 해당 key의 유무를 확인할 수 있음. (boolean 값 반환)
// 동일하게 .hasOwnProperty() 메소드를 이용해도 같은 기능을 수행함.
console.log("name" in dog);
console.log(dog.hasOwnProperty("emoji"));

// 오브젝트의 각각 프로퍼티는, 프로퍼티 디스크립터라고 하는 객체로 저장된다.
const descriptors = Object.getOwnPropertyDescriptors(dog);
console.log(" descriptors : ", descriptors); // key에 대한 디스크립터와 value에 대한 디스크립터가 출력된 것을 확인할 수 있다.

const desc = Object.getOwnPropertyDescriptor(dog, "name");
console.log(" desc : ", desc);

Object.defineProperty(dog, "name", {
  value: "왈왈오랄랄",
  writable: false,
  enumerable: false, // 콘솔에 출력되지 않음.
  configurable: false, // key를 수정할 수 없음.
});

console.log(" dog.name : ", dog.name);
console.log(Object.keys(dog));

// 요약 : 오브젝트는 수정할 수 있는지, 콘솔에 띄울건지의 여부를 정하는 속성을 따로 가지고 있음.
// 프로퍼티 디스크립터는 객체의 프로토타입에서 제공해주는 프로퍼티로 접근 또는 정의가 가능하다 =>
// 접근과 정의가 가능한 정적메서드는 다음과 같다. getOwnPropertyDescriptors, getOwnPropertyDescriptor, defineProperty, defineProperties

// 이번 쳅터 요약 코드
const student = {};
Object.defineProperties(student, {
  firstName: {
    value: "민희",
    writable: true,
    enumerable: true,
    configurable: true,
  },
  lastName: {
    value: "김",
    writable: true,
    enumerable: true,
    configurable: true,
  },
  fullName: {
    get() {
      return `${lastName} ${firstName}`;
    },
    set(name) {
      [this.lastName, this.firstName] = name.split(" ");
    },
    configurable: true,
  },
});
console.log(" student : ", student);
const descriptorsStudent = Object.getOwnPropertyDescriptors(student);
console.log(" descriptorsStudent : ", descriptorsStudent);
student.firstName = "소영";
console.log(student.firstName);

const obj = {
  name: "휘인",
};
obj.name = "정민";
console.log(" obj : ", obj.name);

0개의 댓글