객체 메서드: 축약형 vs 일반형 차이점

    728x90
    반응형
    SMALL

     

    객체 메서드: 축약형 vs 일반형 차이점

    두 가지 작성 방식

    const obj = {
      // 축약형 (ES6+)
      method() {
        return 'hello';
      },
      
      // 일반형
      func: function() {
        return 'hello';
      }
    };
    

     

     

    핵심 차이점

    1. 생성자 사용 가능 여부

    new obj.func();   // ✅ 가능
    new obj.method(); // ❌ TypeError
    

    축약형은 [[Construct]] 내부 슬롯이 없어서 new와 함께 사용할 수 없다.

    2. prototype 프로퍼티

    obj.func.prototype;   // {} - 존재
    obj.method.prototype; // undefined - 없음
    

    생성자로 못 쓰니까 prototype 프로퍼티도 없다. 메모리를 약간 덜 사용한다.

    3. super 키워드

    const parent = { greet() { return 'Hi'; } };
    
    const child = {
      __proto__: parent,
      
      // 축약형 - super 사용 가능
      hello() {
        return super.greet() + ' World';
      },
      
      // 일반형 - super 사용 불가
      hello2: function() {
        return super.greet(); // ❌ SyntaxError
      }
    };
    

    축약형만 [[HomeObject]]를 가지므로 super를 사용할 수 있다.

     

    요약 표

    특성 축약형 method() {} 일반형 func: function() {}
    생성자 사용
    prototype 프로퍼티
    super 사용

    💡 결론: 일반적으로 축약형 사용을 권장한다. 메서드를 생성자로 쓸 일은 거의 없고, super를 쓸 수 있는 장점이 있다.

     

     

    헷갈리기 쉬운 개념: prototype vs __proto__

    한 줄 요약

    • prototype → 내가 생성자로 쓰일 때 인스턴스에게 줄 것
    • __proto__ → 내가 받는 것 (프로퍼티 찾을 때 타고 올라가는 체인)

     

    __proto__ - 모든 객체가 가짐

    프로퍼티를 찾을 때 이 체인을 타고 올라간다.

    const obj = {};
    obj.toString(); // obj에 없음 → obj.__proto__(Object.prototype)에서 찾음

    prototype - 함수만 가짐

    생성자로 사용될 때, 인스턴스의 __proto__가 될 객체를 담아둔다.

    function Person(name) {
      this.name = name;
    }
    Person.prototype.sayHi = function() {
      return `Hi, ${this.name}`;
    };
    
    const me = new Person('Kim');
    // new 할 때 일어나는 일: me.__proto__ = Person.prototype
    me.__proto__ === Person.prototype; // true

     

    프로토타입 체인 예시

    const grandParent = { 
      grand() { return 'grand'; } 
    }; 
    
    const parent = { 
      __proto__: grandParent,
      parent() { return 'parent'; } 
    }; 
    
    const child = { 
      __proto__: parent,
      child() { return 'child'; } 
    }; 
    
    child.child();    // 'child' - child에서 찾음
    child.parent();   // 'parent' - parent에서 찾음
    child.grand();    // 'grand' - grandParent에서 찾음
    child.toString(); // Object.prototype에서 찾음

    체인 흐름: child → parent → grandParent → Object.prototype → null

     

    축약형과 프로토타입

    const obj = {
      method() {},
      func: function() {}
    };
    
    // prototype 프로퍼티 (줄 것)
    obj.func.prototype;   // {} - 생성자로 쓸 수 있으니까 있음
    obj.method.prototype; // undefined - 생성자 아니니까 없음
    
    // __proto__ 체인 (받는 것) - 둘 다 정상 동작
    obj.method.call();  // ✅
    obj.method.apply(); // ✅
    obj.method.bind();  // ✅

    💡 축약형에 prototype이 없다는 건 **"줄 것이 없다"**는 의미지, **"받는 것"**인 프로토타입 체인 접근과는 무관하다.

    728x90
    반응형
    LIST

    댓글