[Javascript]03-5. 프로토타입 체이닝 (2)

Elen li·2021년 10월 30일
0
post-thumbnail

프로토타입도 자바스크립트 객체다.

프로토타입 객체 역시 자바스크립트의 객체이므로 일반 객체처럼 동적으로 프로퍼티를 추가/삭제 하는 것이 가능하다. 이렇게 변경된 프로퍼티는 실시간으로 프로토타입 체이닝에 반영된다.

// 프로토타입 객체의 동적 메서드 생성 예제 코드

// Person() 생성자 함수
function Person(name) {
  this.name = name;
}

// foo 객체 생성
var foo = new Person(‘foo’);
// foo.sayHello(); (에러남)

Person.prototype.sayHello = function () {
  console.log(‘Hello’);
}

foo.sayHello(); // Hello

프로토타입 메서드와 this 바인딩

프로토타입 메서드 내부에서 this를 사용할 경우, this는 메서드를 호출한 객체에 바인딩 된다.

아래 코드에서 살펴보면, Person에 추가된 getName()을 호출하면 생성된 객체에서 넘긴 값에 맞춰 반환하는 것을 확인할 수 있습니다.

// 프로토타입 메서드와 this 바인딩

// Person() 생성자 함수
function Person(name) {
  this.name = name;
}

// getName() 프로토타입 메서드
Person.prototype.getName = function() {
  return this.name;
}

// foo 객체 생성
var foo = new Person(‘foo’);

console.log(foo.getName()); // (출력값) foo

// Person.prototype 객체에 name 프로퍼티 동적 추가
Person.prorotype.name = ‘person’;

console.log(Person.prototype.getName()); // (출력값) person

(p.134)

디폴트 프로토타입은 다른 객체로 변경이 가능하다.

함수가 생성될 때 디폴트 프로토타입 객체가 함께 생성되며, 함수의 prototype 프로퍼티에 연결된다. 이렇게 연결되는 디폴트 프로토타입 객체를 다른 일반 객체로 변경하는 것이 가능하다. 이러한 속성으로 객체지향의 상속을 구현한다.

생성자 함수의 프로토타입 객체가 변경되면, 변경된 시점 이후에 생성된 객체들은 변경된 프로토타입 객체로 [[Prototype]] 링크를 연결한다는 점을 기억해야 합니다.

// 프로토타입 객체 변경

객체의 프로퍼티 읽기나 메서드를 실행할 때만 프로토타입 체이닝이 동작한다.

객체의 특정 프로퍼티를 읽으려고 할 때 프로퍼티가 해당 객체에 없는 경우, 프로토타입 체이닝이 발생합니다. 반대로 객체에 있는 프로퍼티를 사용할 때에는 프로토타입 체이닝이 발생하지 않습니다.

// 프로토타입 체이닝과 동적 프로퍼티 생성

// Person() 생성자 함수
function Person(name) {
  this.name = name;
}

Person.prototype.country = ‘Korea’;

var foo = new Person(‘foo’);
var bar = new Person(‘bar’);
console.log(foo.country);
console.log(bar.country);
foo.country =USA;

console.log(foo.country);
console.log(bar.country);
profile
Android, Flutter 앱 개발자입니다.

0개의 댓글