2017-09-18 3 views
1

방법으로 객체를 확장하는 방법 :ES6 클래스 인스턴스 속성과 나는 다음을 수행 한 이전 ES5 코드베이스에서 일부 코드 리팩토링하고

function ObjectCreatorFunction() { 
    this.someProperty= {}; 
} 

/* 
* Static method, to extend the object passed as a parameter with the 
* ObjectCreatorFunction instance properties and methods 
*/ 
ObjectCreatorFunction.extend = function extend(object) { 
    var key; 

    ObjectCreatorFunction.call(object); 
    for (key in ObjectCreatorFunction.prototype) { 
    if (ObjectCreatorFunction.prototype.hasOwnProperty(key)) { 
     if (!object.hasOwnProperty(key)) { 
     object[key] = ObjectCreatorFunction.prototype[key]; 
     } 
    } 
    } 

    return object; 
}; 

ObjectCreatorFunction.prototype.someMethod = function someMethod() {...} 
//etc 

내가 ES6 재 작성과 동일한 작업을 수행하려고를 그래서 A는이

class ClassName{ 
    constructor() { 
    this.someProperty= {}; 
    } 

    static extend(object) { 
    let key; 

    ClassName.constructor.call(object); 
    for (key in ClassName.prototype) { 
     if (ClassName.prototype.hasOwnProperty(key)) { 
     if (!object.hasOwnProperty(key)) { 
      object[key] = ClassName.prototype[key]; 
     } 
     } 
    } 

    return object; 
    } 

    someMethod() {...} 
    //etc 
} 

내 문제가 전달 된 객체가 클래스의 인스턴스 속성을하지 않는 즉, 의도 한대로 라인이 ClassName.constructor.call(object); 이 작동하지 않는다는 것입니다 있습니다.

나는 이것을 쓸모없는 몇 가지 방법으로 시도해 보았다.

ES6을 사용하여 클래스의 인스턴스 속성을 사용하여 객체를 확장하는 방법은 무엇입니까?

면책 조항 :

내 코드는 바벨과 웹팩과 더불어, transpiling 과정을 통해 전달됩니다. 클래스가 내부적으로 어떻게 작동하는지에 영향을 미칠 경우

+1

"* 전달 된 객체가 클래스의 인스턴스 속성을 가져올 *하지 않습니다"를 - 그게 너의 유일한 관찰 일까? 예외는 없습니까? – Bergi

+2

믹스 인을 쓰고 싶다면'class' 문법을 쓰지 않는 것이 좋습니다. 'function'은 여전히 ​​괜찮습니다. – Bergi

+0

@Bergi 내가 쓰는 방법은 예외가 아니다. 전달 된 객체는 들어 왔을 때와 동일한 결과를 반환합니다. 다른 방식으로 쓰기 만하면됩니다. 'ClassName.call (object)'또는'new className.call (object)''클래스를 함수로 호출 할 수 없습니다. '그리고'className.call은 생성자가 아닙니다'각각 –

답변

1

아니요, 이것은 class 구문과 함께 작동하지 않습니다. 단지 문법적인 설탕보다 a bit more입니다. 프로토 타입 상속은 동일하게 유지되었지만 인스턴스의 초기화는 특히 상속 된 클래스에서 다르게 작동하며 new없이 생성자를 호출하여 새 인스턴스를 만들 수 없습니다.

나는 당신의 믹스 인을 명확히하는 것이 좋습니다, 그것은에게 init 방법 줄 것이다

:

class Mixin { 
    constructor(methods) { 
     this.descriptors = Object.getOwnPrpertyDescriptors(methods); 
    } 
    extend(object) { 
     for (const p of this.descriptors)) { 
      if (Object.prototype.hasOwnProperty.call(o, p)) { 
       if (process.env.NODE_ENV !== 'production') { 
        console.warn(`Object already has property "${p}"`); 
       } 
      } else { 
       Object.defineProperty(o, p, this.descriptors[p]); 
      } 
     } 
    } 
} 

// define a mixin: 
const xy = new Mixin({ 
    initXY() { 
     this.someProperty= {}; 
    }, 
    someMethod() { … } 
}); 
// and use it: 
class ClassName { 
    constructor() { 
     this.initXY(); 
    } 
} 
xy.extend(ClassName.prototype); 
+0

시간을 내 주셔서 감사합니다.하지만이 새로운 레벨의 "추상화"를 소개합니다. 여기서는 클래스를 사용하여 ES5 코드의 효과를 얻는 간단한 방법이 있는지 알고 싶었습니다.가능하지 않다면 유효한 답변이지만 그 이유를 알고 싶습니다. 추신. 내 코드는 바벨 (babel)과 웹팩 (webpack)을 통해 투명화 과정을 거쳐 전달됩니다. 영향을 주는지 확신하지 못합니다. –

+0

'Mixin' 클래스의 추상화를 삭제하고 하나의 객체 리터럴로 모두 덤프 할 수도 있습니다. 하지만 네, 믹스 인을 생성하기 위해'클래스 '를 사용할 수 없습니다. – Bergi

관련 문제