ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 모던 자바스크립트 Deep Dive - 프로퍼티 섀도잉 , 교체 , 정적 프로퍼티
    JavaScript 2021. 9. 23. 22:47

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


    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('Kim');
    
    me.sayHello = function(){
        console.log(`Hello ! My name is ${this.name}`);
    }
    
    me.sayHello();  // Hello ! My name is Kim

    위 예시 코드처럼
    같은 이름의 프로퍼티를 인스턴스에 추가하게되면
    프로토타입 프로퍼티를 덮어쓰는 것이 아니라 인스턴스 프로퍼티로 추가한다.
    즉, 인스턴스 메서드는 오버라이딩했고 , 프로토타입 메서드는 가려졌는데 이 현상을 프로퍼티 섀도잉 이라 한다.

     

    delete me.sayHello;
    
    me.sayHello();  // Hi! ...
    
    delete me.sayHello;
    
    me.sayHello();  // Hi! ...
    
    delete Person.prototype.sayHello;
    
    me.sayHello();  // TypeError

     

     

     

    프로토타입의 교체


    프로토타입은 임의의 다른 객체로 변경할 수 있다.
    즉, 부모 객체인 프로토타입을 동적으로 변경할 수 있다는 것을 의미한다.

    프로토타입은 생성자 함수 또는 인스턴스에 의해 교체할 수 있다.

     

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

    const Person = (function(){
        function Person(name){
            this.name = name;
        }
        
        Person.prototype = {
            sayHello(){
                console.log(`Hi ! My name is ${this.name}`);
            }
        };
        
        return Person;
    }());
    
    const me = new Person('Kim');

    생성자 함수의 prototype 프로퍼티를 통해 프로토타입을 교체하였다.
    Person.prototype에 객체 리터럴로 교체했다.

    prototype으로 교체한 객체 리터럴에는 constructor 프로퍼티가 존재하지 않는다.
    따라서 me 객체의 생성자 함수를 검색하면 Person이 아닌 Object가 나온다.

    console.log(me.constructor === Person);  // false
    console.log(me.constructor === Object);  // true

     

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

     

    const Person = (function(){
        function Person(name){
            this.name = name;
        }
        
        Person.prototype = {
            constructor : Person,
            sayHello(){
                console.log(`Hi! My name is ${this.name}`);
            }
        };
        
        return Person;
    }());
    
    const me = new Person('Kim');
    
    console.log(me.constructor === Person);  //  true
    console.log(me.constructor === Object);  //  false

     

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

    프로토타입은 생성자 함수의 prototype 프로퍼티 뿐만 아니라 인스턴스의 __proto__ 접근자 프로퍼티를 통해 접근할 수 있다.

    function Person(name){
        this.name = name;
    }
    
    const me = new Person('Kim');
    
    const parent = {
        sayHello(){
            console.log(`Hi! My name is ${this.name}`);
        }
    };
    
    Object.setPrototypeOf(me,parent);
    // = me.__proto__ = parent;
    
    me.sayHello();  // Hi! My name is Kim

     

     

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

     

     

    instanceof 연산자


    객체 instanceof 생성자 함수

    우변의 생성자 함수의 prototype에 바인딩된 객체가
    좌변의 객체의 프로토타입 체인 상에 존재하면 true

     

     

    직접 상속


    [ Object.create에 의한 직접 상속 ]

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

    Object.create(프로토타입으로 지정할 객체 , 생성할 객체의 프로퍼티 키와 프로퍼티 디스크립터 객체)

    let obj = Object.create(null);
    
    console.log(Object.getPrototypeOf(obj) === null); // true
    console.log(obj.toString());  // TypeError => Object.prototype을 상속받지 못함
    
    obj = Object.create(Object.prototype);
    console.log(Object.getPrototypeOf(obj) === Object.prototype);  // true
    
    const myProto = { x : 10 };
    
    obj = Object.create(myProto);
    
    console.log(obj.x);  // 10
    console.log(Object.getPrototypeOf(obj) === myProto);
    
    function Person(name){
        this.name = name;
    }
    
    obj = Object.create(Person.prototype);
    obj.name = 'Kim';
    console.log(obj.name); // Kim
    console.log(Object.getPrototypeOf(obj) === Person.prototype);  // true

     

     

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

    const myProto = { x : 10 };
    
    const obj = {
        y : 20,
        __proto__ : myProto
    };
    
    console.log(obj.x,obj.y);  // 10 20
    console.log(Object.getPrototypeOf(obj) === myProto); // true

     

     

     

    정적 프로퍼티 / 메서드


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

    function Person(name){
        this.name = name;
    }
    
    Person.prototype.sayHello = function(){
        console.log(`Hi! My name is ${this.name}`);
    }
    
    Person.staticProp = 'static Prop';
    
    Person.stticMethod = function(){
        console.log('static Method');
    }
    
    const me = new Person('Lee');
    
    Person.staticMethod(); // static Method
    
    me.staticMethod();  // TypeError

     

    Person 생성자 함수는 객체이므로 자신의 프로퍼티 / 메서드를 소유할 수 있다.
    이러한 생성자 함수가 소유하는 프로퍼티 및 메서드를 정적 프로퍼티 메서드라고 한다.

    정적 프로퍼티 및 정적 메서드는 인스턴스가 참조 및 호출할 수 없다.

     

     

    프로퍼티 존재 확인


    [ in 연산자 ]

    key in object

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

    const person = {
        name : 'Kim',
        address : 'Suwon'
    }
    
    console.log('name' in person); //true
    console.log('address' in person); // true
    console.log('age' in person); //false

     

     

    [ Object.prototype.hasOwnProperty 메서드 ]

     

    Object.prototype.hasOwnProperty 메서드를 사용해도 객체에 특정 프로퍼티가 존재하는지 확인할 수 있다.

    console.log(person.hasOwnProperty('name')); // true
    console.log(person.hasOwnProperty('toString')); // false

    hasOwnProperty 메서드는 상속받은 프로토타입의 프로퍼티 또한 false를 반환한다.

     

     

    프로퍼티 열거


    [ for ... in 문 ]

    for ( 변수 선언문 in 객체 ) { ... }
    const person = {
        name : 'Kim',
        address : 'Suwon'
    }
    
    for ( const key in person) {
        consolelog(key + ' : ' + person[key]);
    }
    
    // name : Kim
    // address : Suwon

     

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

    또한 , 순서를 보장하지 않는다.

    따라서, for ... of 나 forEach 메서드 사용 권장한다.

    for ... in 문은 상속받은 프로퍼티 또한 열거한다. 
    따라서, 객체 자신의 프로퍼티가 필요하다면 확인하는 추가 로직을 hasOwnProperty를 사용해서 구현해주어야한다.

     

    [ Object.keys / values / entries 메서드 ]

    • Object.keys : 프로퍼티 키를 배열로 반환한다.
    • Object.values : 프로퍼티 값을 배열로 반환한다.
    • Object.entries : 프로퍼티 키와 값의 쌍의 배열을 배열에 담아 반환한다.

    댓글

Designed by Tistory.