JavaScript - 프로토타입 교체

춤추는개발자·2023년 4월 4일
0
post-thumbnail

프로토타입을 우리가 원하는대로 다른 객체로 변경 할 수 있습니다.

생성자 함수에 의한 프로토타입의 교체

아래의 코드를 확인 해 봅시다.

function SoccerPlayer(name, age, myTeam) {
  this.name = name;
  this.age = age;
  this.myTeam = myTeam;
}

SoccerPlayer.prototype = {
  say() {
    return `저의 이름은 ${this.name} 이고 소속팀은 ${this.myTeam} 입니다.`;
  },
};

const tom = new SoccerPlayer('tom', 3, '토트넘');

console.log(tom.say()); // 저의 이름은 tom 이고 소속팀은 토트넘 입니다.

console.log(tom.constructor === SoccerPlayer) // false
console.log(tom.constructor === Object); // true

위와 같이 SoccerPlayer 생성자 함수의 prototype 프로퍼티가 가리키는
프로토타입을 객체 리터럴로 변경하면 생성자 함수가 생성한 객체의 프로토타입은 해당 객체 리터럴 입니다.

이 객체 리터럴은 constructor 프로퍼티가 없기 때문에 SoccerPlayer 생성자 함수로 생성한 객체의 생성자 함수는 SoccerPlayer 생성자 함수가 아닌 Object 인것을 확인 할 수 있습니다.

이렇게 사용자가 직접 프로토타입을 교체하면 constructor 과 생성자 함수와의 관계가 끊기게 됩니다.
그럼 교체한 프로토타입과 생성자 함수와의 constructor 관계를 다시 만들려면 어떻게 해야 할까요?
교체한 프로토타입 객체에 constructor 프로퍼티를 추가하면 됩니다.

SoccerPlayer.prototype = {
  constructor: SoccerPlayer,
  say() {
    return `저의 이름은 ${this.name} 이고 소속팀은 ${this.myTeam} 입니다.`;
  },
};

console.log(tom.constructor === SoccerPlayer); // true

console.log(tom.constructor === Object); // false

위와 같이 생성자 함수의 프로토타입을 변경할때 변경할 객체에 constructor 프로퍼티를 추가하고 값을 생성자 함수로 지정하면 생성한 객체의 생성자 함수는
SoccerPlayer 가 됩니다.

인스턴스에 의한 프로토타입 교체

이미 생성한 인스턴스에서 __proto__ 를 이용해서 프로토타입을 교체 할 수 있습니다.
생성자함수.prototype 방법으로 프로토타입 교체를 하는것과 같은 점은 역시나 교체한 프로토타입에는 constructor 가 없기 때문에 생성자 함수와 프로토타입 객체 간의 관계가 끊겼다는 것이고 다른점은 생성자함수.prototype 으로 교체했을때는 생성자함수의 prototype 프로퍼티는 교체한 프로토타입 객체를 가리키고 있지만 __proto__ 로 프로토타입을 교체하면 생성자함수의 prototype 프로퍼티는 이전의 프로토타입 객체를 가리키고 있다는 것 입니다.

여기서도 교체할 객체에 constructor 프로퍼티에 생성자 함수 값을 추가하고 생성자 함수의 prototype 프로퍼티에 교체할 객체를 설정하면 생성자 함수와 교체하는 프로토타입의 관계를 다시 연결 할 수 있습니다.

prototype 프로퍼티로 프로토타입을 교체하는 것과 __proto__ 로 교체하는 하는것의 다른점은 __proto__ 로 프로토타입을 교체하는 것은 이미 생성된 객체의 프로토타입을 교체하는 것이기 때문에 이후에 생성자함수로 생성한 객체는 원래 프로토타입을 프로토타입으로 가지게 됩니다. 하지만 생성자 함수의 prototype 프로퍼티로 프로토타입을 교체하게되면 이후부터 생성자 함수로 생성하는 모든 객체의 프로토타입은 교체한 프로토타입 객체 입니다.

0개의 댓글