[javascript] 프로퍼티 디스크립터와 객체 상속 관계

자바스크립트에서 객체가 상속받은 프로퍼티에 대해서 알아보고, 상속받은 프로퍼티와 자체 프로퍼티 간의 관계를 다루는 프로퍼티 디스크립터에 대해 알아보겠습니다.

객체 상속

자바스크립트에서 객체는 프로토타입 체인을 통해 다른 객체로부터 프로퍼티를 상속받을 수 있습니다. 이를 이용하여 코드의 재사용성을 높일 수 있고, 객체 간에 관계를 구성할 수 있습니다.

예를 들어, 다음과 같이 Person 객체를 선언하고 이를 상속받은 Student 객체를 생성할 수 있습니다.

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

Person.prototype.sayHello = function() {
  console.log("Hello, my name is " + this.name);
};

function Student(name, grade) {
  Person.call(this, name);
  this.grade = grade;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

var student = new Student("John", 10);
student.sayHello(); // "Hello, my name is John"

위의 예제에서 Student 객체는 Person 객체를 상속받아 name 프로퍼티와 sayHello 메소드를 사용할 수 있습니다.

프로퍼티 디스크립터

프로퍼티 디스크립터는 객체의 프로퍼티를 설명하는 객체입니다. 프로퍼티 디스크립터는 Object.defineProperty() 함수를 사용하여 설정할 수 있습니다.

객체의 프로퍼티에 대한 프로퍼티 디스크립터는 다음과 같은 속성을 가질 수 있습니다.

var obj = {};

Object.defineProperty(obj, "name", {
  value: "John",
  writable: true,
  enumerable: true,
  configurable: true
});

프로퍼티 디스크립터를 사용하여 프로퍼티의 속성을 설정할 수 있습니다. 위의 예제에서 name 프로퍼티는 값이 변경 가능하고 열거 가능하며 디스크립터도 변경 가능합니다.

객체 상속과 프로퍼티 디스크립터

객체가 상속받은 프로퍼티와 자체 프로퍼티의 관계는 프로퍼티 디스크립터를 통해 조작할 수 있습니다.

예를 들어, 다음과 같이 Person 객체를 상속받은 Student 객체를 선언합니다.

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

Person.prototype.sayHello = function() {
  console.log("Hello, my name is " + this.name);
};

function Student(name, grade) {
  Person.call(this, name);
  this.grade = grade;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

위의 예제에서 Person 객체의 age 프로퍼티는 상속받는 Student 객체에서도 사용할 수 있습니다. 이때, age 프로퍼티는 상속받은 프로퍼티이기 때문에 프로퍼티 디스크립터를 이용하여 속성을 조작할 수 있습니다.

var student = new Student("John", 10);

// 프로퍼티 디스크립터를 사용하여 age 프로퍼티의 속성 수정
Object.defineProperty(student, "age", {
  writable: false
});

student.age = 30; // 에러 발생
console.log(student.age); // 20

위의 예제에서 age 프로퍼티의 값을 변경할 수 없도록 속성을 설정하여 프로퍼티 디스크립터를 변경합니다. 이제 student 객체의 age 프로퍼티의 값은 변경할 수 없습니다.

결론

자바스크립트에서 객체의 상속과 프로퍼티 디스크립터를 이용하여 객체 간의 관계를 구성하고 프로퍼티의 속성을 조작할 수 있습니다. 이를 이용하면 코드의 재사용성을 높일 수 있고, 객체의 동작에 대한 제어도 가능해집니다.