2017-11-16 3 views
0

클래스를 만드는 방법이 있으며 클래스 생성자 메서드에서 다른 정보와 함께 다른 클래스의 두 객체를 전달합니다. 예를 들어 세 개의 클래스, Statistics 클래스, Attributes 클래스 및 Character 클래스가 있다고 가정합니다. 그들은 같은 종류의 모양 :ES6 자바 스크립트 클래스

class Statistics { 
    constructor(stren, dex, wis, cha, armorClass, hitPoints) { 
     this._stren = stren; 
     this._dex = dex; 
     this._wis = wis; 
     this._cha = cha; 
     this._armorClass = armorClass; 
     this._hitPoints = hitPoints; 
    } 
} 

class Attributes { 
    constructor(name, race, sex, level, height, weight, speed) { 
     this._name = name; 
     this._race = race; 
     this._sex = sex; 
     this._level = level; 
     this._height = height; 
     this._weight = weight; 
     this._speed = speed; 
    } 
} 

문자 클래스 이후 '생성자는 13 개 세 이상 인자있을 것입니다, 나는 다른 클래스로 분리 낸 13 개 세 이상 인수 생성자를 작성하는 것보다 더 나은했다.

class Character { 
    constructor(Statistics statistic, Attributes attributes) { 
     ..... 
    } 
} 

편집 : 그래서 비슷한 할 수있는 방법이 아니,이 질문의 중복 아닌 사람들도 실제로 읽습니까 질문은 중복이 있다는 말을하기 전에 무엇을 요구하고 있는가?

+2

예와 아니오 ...'생성자 (통계, 속성)'- 두 인수 생성자 –

+0

의 오른쪽 클래스의 있는지 확인하는 새로운 전달 문제 있나요 객체를'Character' 클래스에 인자로 넣을까요? "typechecking"이없는 포괄적 인 주장입니다. – Andrew

+0

'Character'가 통계/속성의 모든 속성을 가져 오도록 하시겠습니까? 그렇다면 여기에 어떻게하는지 보여주는 바이올린이 있습니다. https://jsfiddle.net/fhnqh2og/ – IrkenInvader

답변

1

클래스는 문법적인 설탕이므로 Object.defineProperty으로 Character 프로토 타입을 추가하고 직접 게터를 만들 수 있습니다.

편집 : DRYd it up with a loop.

class Statistics { 
 
    constructor(stren, dex, wis, cha, armorClass, hitPoints) { 
 
     this._stren = stren; 
 
     this._dex = dex; 
 
     this._wis = wis; 
 
     this._cha = cha; 
 
     this._armorClass = armorClass; 
 
     this._hitPoints = hitPoints; 
 
    } 
 
} 
 

 
class Attributes { 
 
    constructor(name, race, sex, level, height, weight, speed) { 
 
     this._name = name; 
 
     this._race = race; 
 
     this._sex = sex; 
 
     this._level = level; 
 
     this._height = height; 
 
     this._weight = weight; 
 
     this._speed = speed; 
 
    } 
 
} 
 

 
class Character { 
 
    constructor(statistics, attributes) { 
 
     this.buildGetters(attributes) 
 
     this.buildGetters(statistics) 
 
     } 
 
     
 
     buildGetters(obj) { 
 
     for (let attr in obj){ 
 
      Object.defineProperty(Character.prototype, attr.replace("_", ""), { 
 
      get: function() { 
 
       return obj[attr] 
 
      } 
 
      }) 
 
     } 
 
     } 
 
} 
 

 

 
const stats = new Statistics() 
 
const attr = new Attributes("Mike") 
 
const mike = new Character(stats, attr) 
 
console.log(mike.name);

+1

왜'Character()'클래스에'get name() {return this._attributes._name}'을 쓰지 않으시겠습니까? 'Object.defineProperty'는 다른 이름으로 속성을 동적으로 생성하고자 할 때만 필요합니다. – Bergi

+0

이 문서를 보여줄 수 있습니까? ES5 생성자에서'get '이 작동한다는 것을 알았지 만 클래스 구문과 함께 작동하지 않는다는 인상하에있었습니다. – Andrew

+0

답변 해 주셔서 감사합니다!그게 내가 한 일이야. 나는 그 일을 13 번하는 것이 오히려 시간이 많이 걸리고 많은 공간을 차지한다는 것에 동의한다. 더 나은 방법으로 그 일을하는 방법에 대한 제안? – Mike