19.7 프로토타입 체인  

// 예제 19-29
function Person(name) {
    this.name = name; 
}

// 프로토타일 메서드 
Person.prototype.sayHello = function () {
    console.log(`Hi! My name is ${this.name}`); 
};

const me = new Person('Lee');

// hasOwnProperty는 object.prototype의 메서드다. 
console.log(me.hasOwnProperty('name')); // true

- Person 생성자 함수에 의해 생성된 me 객체는 Object.prototype의 메서드인 hasOwnProperty를 호출할 수 있다.

- 이것은 me 객체가 Object.prototype도 상속받았다는 것을 의미. me 객체 프로토타입은 Person.prototype.

 

- Person.prototype의 프로토타입은 Object.prototype이다.

- 프로토타입의 프로토타입은 언제나 Object.prototype이다.

(19-18 그림 추가)

 

- 자바스크립트는 객체의 프로퍼티(메서드 포함)에 접근하려고 할 때 해당 객체에 접근하려는 프로퍼티가 없다면 [[Prototype]] 내부 슬롯의 참조를 따라 자신의 부모 역할을 하는 프로토타입의 프로퍼티를 순차적으로 검색한다.

- 프로토타입 체인. 객체지향 프로그래밍의 상속을 구현하는 메커니즘.

 

1. 먼저 hasOwnProperty 메서드를 호출한 me 객체에서 hasOwnProperty 메서드를 검색한다.

me 객체에는 hasOwnProperty 메서드가 없으므로 [[Prototype]] 내부 슬롯에 바인딩되어 있는 프로토타입(위 예제의 경우 Person.prototype)으로 이동하여 hasOwnProperty 메서드를 검색.

 

2. Person.prototype에도 hasOwnProperty 메서드가 없으므로 [[Prototype]] 내부 슬롯에 바인딩되어 있는 프로토타입으로 이동하여 hasOwnProperty 메서드를 검색한다.

 

3. Object.prototype에는 hasOwnProperty 메서드가 존재한다. 자바스크립트 엔진은 Object.prototype.hasOwnProperty 메서드를 호출한다. 이때 Object.prototype.hasOwnProperty 메서드의 this에는 me 객체가 바인딩된다.

 

- 프로토타입 체인의 최상위에 위치하는 객체는 언제나 Object.prototype.

- Object.prototype을 프로토타입 체인의 종점이라 함. [[Prototype]] 내부 슬롯의 값은 null이다.

- Object.prototype에서도 프로퍼티를 검색할 수 없는 경우 undefined를 반환한다. 이때 에러가 발생하지 않는다.

 

- 프로토타입 체인. 상속과 프로퍼티 검색을 위한 메커니즘.

- 스코프 체인. 식별자 검색을 위한 메커니즘.

 

- 스코프 체인과 프로토타입 체인은 서로 연관 없이 별도로 동작하는 것이 아니라 서로 협력하여 식별자와 프로퍼티를 검색하는 데 사용.

  19.8 오버 라이딩과 프로퍼티 섀도잉  

// 예제 19-36
const Person = (function () {
    // 생성자 함수 
    function Person(name) {
         this.name = name; 
    }

    // 프로토타입 메서드 
    Person.prototype.sayHello = function () {
        console.log(`Hi! My name is ${this.name}`); 
    };
    
    // 생성자 함수를 반환
    return Person;
}());
const me = new Person('Lee');

// 인스턴스 메서드
me.sayHello = function () {
    console.log(`Hey! My name is ${this.name}`);
};

// 인스턴스 메서드가 호출된다. 프로토타입 메서드는 인스턴스 메서드에 의해 가려진다. 
me.sayHello(); // Hey! My name is Lee

(19-19 그림 추가)

 인스턴스 프로퍼티 : 프로토타입이 소유한 프로퍼티(메서드 포함)를 프로토타입 프로퍼티, 인스턴스가 소유한 프로퍼티.

- 프로토타입 프로퍼티와 같은 이름의 프로퍼티를 인스턴스에 추가하면 프로퍼티를 덮어쓰는 것이 아니라 인스턴스 프로퍼티로 추가.

 프로퍼티 섀도잉 : 상속 관계에 의해 프로퍼티가 가려지는 현상.

 

- 오버 라이딩 : 상위 클래스가 가지고 있는 메서드를 하위 클래스가 재정의하여 사용하는 방식

- 오버 로딩 : 함수의 이름은 동일하지만 매개변수의 타입 또는 개수가 다른 메서드를 구현하고 매개변수에 의해 메서드를 구별하여 호출하는 방식. 자바스크립트는 arguments 객체 사용하여 구현.

 

- 하위 객체를 통해 프로토타입의 프로퍼티를 변경 또는 삭제하는 것은 불가능

- get 액세스는 허용되나 set 액세스는 허용되지 않음.

- 프로토타입 체인으로 접근하는 것이 아니라 프로토타입에 직접 접근해야 함.

  19.9 프로토타입의 교체  

  19.9.1 __proto__ 접근자 프로퍼티  

// 예제 19-40
const Person = (function() {
    function Person(name) {
        this.name = name; 
    }

    // ① 생성자 함수의 prototype 프로퍼티를 통해 프로토타입을 교체 
    Person.prototype = {
        sayHello() {
            console.log(`Hi! My name is ${this.name}`);
        } 
    };
    return Person; 
}());
const me = new Person('Lee');

- ①에서 Person.prototype에 객체 리터럴을 할당.

- Person 생성자 함수가 생성할 객체의 프로토타입을 객체 리터럴로 교체한 것.

(19-20 그림 추가)

- me 객체의 생성자 함수를 검색하면 Person이 아닌 Object 나옴.

 

- 프로토타입을 교체하면 constructor 프로퍼티와 생성자 함수 간의 연결이 파괴됨.

- 프로토타입으로 교체한 객체 리터럴에 constructor 프로퍼티를 추가하여 되살린다.

// 예제 19-42
const Person = (function () {
    function Person(name) {
        this.name = name
    }

    // 생성자 함수의 prototype 프로퍼티를 통해 프로토타입을 교체 
    Person.prototype = {
        // constructor 프로퍼티와 생성자 함수 간의 연결을 설정 
        constructor: Person, sayHello() {
            console.log(`Hi! My name is ${this.name}`); 
        }
    };
    return Person; 
}());

const me = new Person('Lee');

// constructor 프로퍼티가 생성자 함수를 가리킨다. 
console.log(me. constructor === Person); // true 
console.log(me.constructor === Object); // false

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

 

- 생성자 함수의 prototype 프로퍼티에 다른 임의의 객체를 바인딩하는 것은 미래에 생성할 인스턴스의 프로토타입을 교체하는 것이다.

- __proto__ 접근자 프로퍼티를 통해 프로토타입을 교체하는 것은 이미 생성된 객체의 프로토타입을 교제하는 것.

// 예제 19-43
function Person(name) {
    this.name = name; 
}

const me = new Person('Lee');

// 프로토타입으로 교체할 객체 
const parent = {
    sayHello() {
        console.log(`Hi! My name is ${this.name}`);
    } 
};

// ① me 객체의 프로토타입을 parent 객체로 교체한다.
Object.setPrototypeof(me, parent);
// 위 코드는 아래의 코드와 동일하게 동작한다. 
// me.__proto__ = parent

me.sayHello(); // Hi! My name is Lee

(19-21 그림 추가)

- 프로토타입으로 교체한 객체에는 constructor 프로퍼티가 없으므로 프로퍼티와 생성자 함수 간의 연결이 파괴.

- 프로토타입의 constructor 프로퍼티로 me 객체의 생성자 함수를 검색하면 Person이 아닌 Object가 나옴.

(19-22 그림 추가)

 

- 아래는 프로토타입으로 교체한 객체 리터럴에 constructor 프로퍼티를 추가하고 생성자 함수의 prototype 프로퍼티를 재설정하여 파괴된 생성자 함수와 프로토타입 간의 연결을 되살리는 예제이다.

// 예제 19-45
function Person(name) {
    this.name = name; 
}

const me = new Person('Lee');

// 프로토타입으로 교체할 객체 
const parent = { 
    // constructor 프로퍼티와 생성자 함수 간의 연결을 설정 
    constructor: Person, sayHello() {
        console.log(`Hi! My name is ${this.name}`);
    } 
};

// 생성자 함수의 prototype 프로퍼티와 프로토타입 간의 연결을 설정 
Person.prototype = parent;

// me 객체의 프로토타입을 parent 객체로 교체한다. 
Object.setPrototypeof(me, parent);

// 위 코드는 아래의 코드와 동일하게 동작한다. 
// me.__proto__ = parent;

me.sayHello(); // Hi! My name is Lee

// constructor 프로퍼티가 생성자 함수를 가리킨다. 
console.log(me.constructor === Person); // true 
console.log(me.constructor === Object); // false

// 생성자 함수의 prototype 프로퍼티가 교체된 프로토타입을 가리킨다. 
console.log( Person.prototype === Object.getPrototypeOf(me)); // true

- 프로토타입 교체로 객체 간의 상속 관계를 동적 변경하는 것은 번거롭기 때문에 직접 교체하지 않는 것이 좋다.

- 또는 ES6에서 도입된 클래스를 사용하면 간편하고 직관적으로 상속관계를 구현할 수 있음. 

  19.10 instanceof 연산자  

// 예제 19-46
// 생성자 함수 
function Person(name) {
    this.name = name; 
}

const me = new Person('Lee');

// Person.prototypei me 객체의 프로토타입 체인 상에 존재하므로 true로 평가된다. 
console.log(me instanceof Person); // true

// Object.prototypei me 객체의 프로토타입 체인 상에 존재하므로 true로 평가된다. 
console.log(me instanceof Object); // true​

- 우변의 생성자 함수의 prototype에 바인딩된 객체가 좌변의 객체의 프로토타입 체인 상에 존재하면 true로 평가, 그렇지 않으면 false로 평가.

// 예제 19-47
// 생성자 함수 
function Person(name) {
    this.name = name;
}

const me = new Person('Lee');

// 프로토타입으로 교체할 객체 
const parent = {};

// 프로토타입의 교체 
Object.setPrototypeof(me, parent);

// Person 생성자 함수와 parent 객체는 연결되어 있지 않다. 
console.log(Person.prototype === parent); // false 
console.log(parent.constructor === Person); // false

// Person.prototypeo me 객체의 프로토타입 제인 상에 존재하지 않기 때문에 false로 평가된다.
console.log(me instanceof Person); // false

// Object.prototyper me 객체의 프로토타입 제인 상에 존재하므로 true로 평가된다. 
console.log(me instanceof Object); // true

- 프로토타입으로 교체한 parent 객체를 Person 생성자 함수의 prototype 프로퍼티에 바인딩하면 me instanceof Person은 true로 평가될 것

// 예제 19-48
// 생성자 함수 
function Person(name) {
    this.name = name; 
}
const me = new Person('Lee');

// 프로토타입으로 교체할 객체 
const parent = {};

// 프로토타입의 교체 
Object.setPrototypeOf(me, parent);

// Person 생성자 함수와 parent 객체는 연결되어 있지 않다. 
console.log(Person.prototype === parent); // false 
console.log(parent.constructor === Person); // false

// parent 객체를 Person 생성자 함수의 prototype 프로퍼티에 바인딩한다. 
Person.prototype = parent;

// Person.prototypei me 객체의 프로토타입 체인 상에 존재하므로 true로 평가된다. 
console.log(me instanceof Person); // true

// object.prototyper me 객체의 프로토타입 체인 상에 존재하므로 true로 평가된다. 
console.log(me instanceof Object); // true

- instanceof 연산자는 프로토타입의 constructor 프로퍼티가 가리키는 생성자 함수를 찾는 것이 아니라 생성자 함수의 prototype에 바인딩된 객체가 프로토타입 체인 상에 존재하는지 확인.

(19-23 그림 추가)

 

- me instanceof Person, me 객체의 프로토타입 체인 상에 Person.prototype에 바인딩된 객체가 존재하는지 확인.

- me instanceof Object, me 객체의 프로토타입 체인 상에 Object.prototype에 바인딩된 객체가 객체가 존재하는지 확인한다.

 

// 예제 19-49 
function isInstanceof(instance, constructor) {
    // 프로토타입 취득 
    const prototype = Object.getPrototypeof(instance)

    // 재귀 탈출 조건 
    // prototypeol null이면 프로토타입 체인의 종점에 다다른 것이다. 
    if (prototype === null) return false;

    // 프로토타입이 생성자 함수의 prototype 프로퍼티에 바인딩된 객체라면 true를 반환한다. 
    // 그렇지 않다면 재귀 호출로 프로토타입 체인 상의 상위 프로토타입으로 이동하여 확인한다.
    return prototype == constructor.prototype || isInstanceof(prototype, constructor);
}

console.log(isInstanceof(me, Person)); // true 
console.log(isInstanceof(me, Object)); // true 
console.log(isInstanceof(me, Array)); // false

- instanceof 연산자를 함수로 표현한 예제이다.

// 예제 19-50
const Person = (function () {
    function Person (name) {
        this.name = name; 
    }

    // 생성자 함수의 prototype 프로퍼티를 통해 프로토타입을 교체 
    Person.prototype={
        sayHello(){
            console.log(`Hi! My name is ${this.name}`); 
        } 
    };
    return Person; 
}());

const me = new Person('Lee');

// constructor 프로퍼티와 생성자 함수 간의 연결이 파괴되어도 instanceof는 아무런 영향을 받지 않는다. 
console.log(me.constructor === Person); // false

// Person.prototyper me 객체의 프로토타입 체인 상에 존재하므로 true로 평가된다. 
console.log(me instanceof Person); // true 

// Object.prototypeol me 객체의 프로토타입 체인 상에 존재하므로 true로 평가된다. 
console.log(me instanceof Object); // true

- 프로퍼티와 생성자 함수 간의 연결이 파괴되어도 생성자 함수의 prototype 프로퍼티와 프로토타입 간의 연결은 파괴되지 않으므로 instanceof는 아무런 영향을 받지 않음.

  19.11 직접 상속  

  19.11.1 Object.create에 의한 직접 상속  

- Object.create 메서드는 명시적으로 프로토타입을 지정하여 새로운 객체를 생성.

- Object.create 메서드도 추상 연산 OrdinaryobjectCreate를 호출.

 

- 첫 번째 매개변수에는 생성할 객체의 프로토타입으로 지정할 객체를 전달.

- 두 번째 매개변수에는 생성할 객체의 프로퍼티 키와 프로퍼티 디스크립터 객체로 이뤄진 객체를 전달.

- Object.defineProperties 메서드의 두 번째 인수와 동일. 두 번째 인수는 생략 가능.

/**
 * 지정된 프로토타입 및 프로퍼티를 갖는 새로운 객체를 생성하여 반환한다. 
 * @param {Object} prototype - 생성할 객체의 프로토타입으로 지정할 객체 
 * @param {Object} [propertiesObject] - 생성할 객체의 프로퍼티를 갖는 객체 
 * @returns {Object} 지정된 프로토타입 및 프로퍼티를 갖는 새로운 객체
 */
Object.create(prototype[, propertiesObject])
// 예제 19-51
// 프로토타입이 null인 객체를 생성한다. 생성된 객체는 프로토타입 체인의 종점에 위치한다. 
// obj → null 
let obj = Object.create(null);
console.log(object.getPrototypeof(obj) === null); // true
// Object.prototype을 상속받지 못한다. 
console.log(obj.toString()); // TypeError: obj.toString is not a function

// obj → Object.prototype → null 
// obj = {};와 동일하다. 
obj = Object.create(Object.prototype); 
console.log(object.getPrototypeof(obj) === Object.prototype); // true

// obj→ Object.prototype → null
// obj = { x: 1 };와 동일하다. 
obj = Object.create(Object.prototype, {
    x: { value: 1, writable: true, enumerable: true, configurable: true }
});

// 위 코드는 아래와 동일하다.
// obj = Object.create(object.prototype); 
// obj.x = 1; 
console.log(obj.x); // 1 
console.log(object.getPrototypeof(obj) === Object.prototype); // true

const myProto = { x: 10 }; 
// 임의의 객체를 직접 상속받는다. 
// obj → myProto → Object.prototype → null 
obj = Object.create(myProto); 
console.log(obj.x); // 10 
console.log(object.getPrototypeof(obj) === myProto); // true

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

// obj → Person.prototype → Object.prototype → null 
// obj = new Person('Lee')와 동일하다.
obj = Object.create(Person.prototype);
obj.name = 'Lee'; 
console.log(obj.name); // Lee 
console.log(Object.getPrototypeOf(obj) === Person.prototype); // true

- Object.create 메서드의 장점은 다음과 같다.

  • new 연산자가 없이도 객체를 생성할 수 있다.
  • 프로토타입을 지정하면서 객체를 생성할 수 있다.
  • 객체 리터럴에 의해 생성된 객체도 상속받을 수 있다.
 

- Object.prototype의 빌트인 메서드는 모든 객체의 프로토타입 체인의 종점 메서드이므로 모든 객체가 상속받아 호출할 수 있다.

 

- ESLint에서는 빌트인 메서드를 객체가 직접 호출하는 것을 권장하지 않음.

- 프로토타입 체인의 종점에 위치하는 객체는 Object.prototype의 빌트인 메서드를 사용할 수 없다.

// 예제 19-54
// 프로토타입이 null인 객체를 생성한다.
const obj = Object.create(null);
obj.a = 1;

// console.log(obj.hasOwn Property('a')); 
// TypeError: obj.hasOwn Property is not a function

// Object.prototype의 빌트인 메서드는 객체로 직접 호출하지 않는다. 
console.log(object.prototype.hasOwnProperty.call(obj, 'a')); // true

- 에러를 발생시킬 위험을 없애기 위해 Object.prototype의 빌트인 메서드는 간접적으로 호출하는 것이 좋음.

  19.11.2 객체 리터럴 내부에서 __proto__에 의한 직접 상속  

- Object.create 메서드에 의한 직접 상속은 여러 장점이 있지만 두 번째 인자로 프로퍼티를 정의하는 것은 번거롭다.

- ES6에서는 객체 리터럴 내부에서 __proto__ 접근자 프로퍼티를 사용하여 직접 상속을 구현할 수 있다.

// 예제 19-55
const myProto = { x: 10 };

// 객체 리터럴에 의해 객체를 생성하면서 프로토타입을 지정하여 직접 상속받을 수 있다. 
const obj = { 
    y: 20, 
    // 객체를 직접 상속받는다. 
    // obj → myProto → Object.prototype → null
    __proto__: myProto 
}; 
/* 위 코드는 아래와 동일하다. 
const obj = Object.create(myProto, {
    y: { value: 20, writable: true, enumerable: true, configurable: true }
});
*/
console.log(obj.x, obj.y); // 10 20 
console.log(object.getPrototypeof(obj) === myProto); // true

  19.12 정적 프로퍼티/메서드  

 정적 프로퍼티/메서드 : 생성자 함수로 인스턴스를 생성하지 않아도 참조/호출할 수 있는 프로퍼티/메서드.

// 예제 19-56
// 생성자 함수 
function Person(name) {
    this.name = name; 
}

// 프로토타입 메서드 
Person.prototype.sayHello = function () {
    console.log( `Hi! My name is ${this.name}`); 
};

// 정적 프로퍼티 
Person.staticProp = 'static prop';

// 정적 메서드 
Person.staticMethod = function () {
    console.log('staticMethod'); 
};

const me = new Person('Lee');

// 생성자 함수에 추가한 정적 프로퍼티/메서드는 생성자 함수로 참조/호출한다. 
Person.staticMethod(); // staticMethod

// 정적 프로퍼티 / 메서드는 생성자 함수가 생성한 인스턴스로 참조/호출할 수 없다. 
// 인스턴스로 참조 호출할 수 있는 프로퍼티/메서드는 프로토타입 체인 상에 존재해야 한다. 
me.staticMethod(); // TypeError: me.staticMethod is not a function

- 정적 프로퍼티/메서드는 생성자 함수가 생성한 인스턴스로 참조/호출할 수 없다.

(19-24 그림 추가)

- 정적 프로퍼티/메서드는 인스턴스의 프로토타입 체인에 속한 객체의 프로퍼티/메서드가 아니므로 인스턴스로 접근할 수 없다.

- 프로토타입 메서드를 호출하려면 인스턴스를 생성해야 하지만 정적 메서드는 인스턴스를 생성하지 않아도 호출할 수 있다.

- 프로토타입 프로퍼티/메서드를 표기할 때 prototype을 #으로 표기하는 것 알아두기.

 

  19.13 프로퍼티 존재 확인  

  19.13.1 in 연산자  

- in 연산자는 객체 내에 특정 프로퍼티가 존재하는지 여부를 확인

/**
 * key: 프로퍼티 키를 나타내는 문자열
 * object: 객체로 평가되는 표현식
 */
key in object

- in 연산자는 확인 대상 객체의 프로퍼티뿐만 아니라 확인 대상 객체가 상속받은 모든 프로토타입의 프로퍼티를 확인하므로 주의가 필요하다.

- ES6에서 도입된 Reflect.has 메서드 사용가능. 동일하게 동작한다.

 

  19.13.2 Object.prototype.hasOwnProperty 메서드  

- Object.prototype.hasOwnProperty 메서드 사용 시 객체에 특정 프로퍼티가 존재하는지 확인 가능.

- 인수로 전달받은 프로퍼티 키가 객체 고유의 프로퍼티 키인 경우에만 true를 반환하고 상속받은 프로토타입의 프로퍼티 키인 경우 false를 반환.

  19.14 프로퍼티 열거  

  19.14.1 for ... in 문  

- for... in 객체의 모든 프로퍼티를 순회하며 열거하려면 for... in 문을 사용.

for (변수선언문 in 객체) { ... }
// 예제 19-64
const person = { 
    name: 'Lee',
    address: 'Seoul'
};

// for... in 문의 변수 propol person 객체의 프로퍼티 키가 할당된다. 
for (const key in person) {
    console.log(key + ' :' + person[key]); 
} 
// name: Lee 
// address: Seoul

- for ... in 문은 객체의 프로퍼티 개수만큼 순회하며 for... in 문의 변수 선언문에서 선언한 변수에 프로퍼티 키를 할당

- 상속받은 프로토타입의 프로퍼티까지 열거

 

- for ... in 문은 객체의 프로토타입 체인 상에 존재하는 모든 프로토타입의 프로퍼티 중에서 프로퍼티 어트리뷰트 [[Enumerable]]의 값이 true인 프로퍼티를 순회하며 열거.

// 예제 19-67
const person = {
    name: 'Lee', 
    address: 'Seoul',
    __proto__ : { age: 20 } 
};
for (cons key in person) {
    console.log(key + ':' + person[key]); 
} 
// name: Lee 
// address: Seoul 
// age: 20

- for... in 문은 프로퍼티 키가 심벌인 프로퍼티는 열거하지 않음.

- 상속받은 프로퍼티는 제외하고 객체 자신의 프로퍼티만 열거하려면 Object.prototype.hasOwnProperty 메서드를 사용하여 객체 자신의 프로퍼티인지 확인함.

 

- for ... in 문은 프로퍼티를 열거할 때 순서를 보장하지 않으므로 주의.

- 대부분의 모던 브라우저는 순서를 보장하고 숫자인 프로퍼티 키에 대해서는 정렬 실시.

 

- 배열에는 for... in 문을 사용하지 말고 일반적인 for 문이나 for... of 문 또는 Array.prototype.forEach 메서드를 사용하기를 권장.

- 배열도 객체이므로 프로퍼티와 상속받은 프로퍼티가 포함될 수 있음.

  19.14.2 Object.keys/values/entries 메서드  

- 객체 자신의 고유 프로퍼티만 열거하기 위해 Object.keys/values/entries 메서드를 사용하는 것을 권장.

- 객체 자신의 열거 가능한 프로퍼티 값을 배열로 반환.

- ES8에서 도입된 Object.entries 메서드는 객체 자신의 열거 가능한 프로퍼티 키와 값의 쌍의 배열을 배열에 담아 반환.


* 위 내용은 모던 자바스크립트 Deep Dive를 참고하여 개인적인 공부를 목적으로 정리하였습니다.

http://www.kyobobook.co.kr/product/detailViewKor.laf?ejkGb=KOR&mallGb=KOR&barcode=9791158392239&orderClick=LEa&Kc=

 

모던 자바스크립트 Deep Dive - 교보문고

자바스크립트의 기본 개념과 동작 원리 | 웹페이지의 단순한 보조 기능을 처리하기 위한 제한적인 용도로 태어난 자바스크립트는 과도하다고 느껴질 만큼 친절한 프로그래밍 언어입니다. 이러

www.kyobobook.co.kr