繁体   English   中英

如何在ES6类中的方法中使用组合?

[英]How can I use composition with methods in ES6 Classes?

我正在努力在ES6类中实现合成! 我试图一次理解很多事情,并且可能犯了一个愚蠢的错误。

我现在想避免使用extendsuper进行继承,并且发现了这个很好的合成示例,它似乎表明了我的追求:

class EmployeeTaxData {
  constructor(ssn, salary) {
    this.ssn = ssn;
    this.salary = salary;
  }
  // ...
}

class Employee {
  constructor(name, email) {
    this.name = name;
    this.email = email;
  }

  setTaxData(ssn, salary) {
    this.taxData = new EmployeeTaxData(ssn, salary);
  }
  // ...
}

关于下面的代码,我想使用最简单和雄辩的方法使spin()方法可用于Hero类创建的对象,因此它使用的是共享原型。 我想与也需要它的其他对象共享此方法。

不幸的是,我无法使我的代码正常工作,因为this.angle不是指它需要的Hero类,而是Spinner类?

class Spinner {

  constructor(direction){
    this.direction = direction;
  }

  spin(direction) {
    switch (direction) {
      case 'left':
        this.angle -= 1;
        break;
      case 'right':
        this.angle += 1;
        break;
        // no default
    }
  }
}

class Hero {

  constructor(xPosition, yPosition) {
    this.description = 'hero';
    this.width = 25;
    this.height = 50;
    this.xPosition = xPosition;
    this.yPosition = yPosition;
    this.angle = 0;
    this.color = 'red';
    this.spin = new Spinner();
  }

  spin() {
    this.spin.spin();
  }

}

const heroClass = new Hero(100, 200);

console.log(heroClass.angle); // result is 0
heroClass.spin.spin('left');
console.log(heroClass.angle); // result is STILL 0, it didn't work

... this.angle不是指它需要的Hero类,而是Spinner类?

正如它应该。 当您位于Spinner类内部时, this是指一个Spinner对象,这也意味着该对象this.angle类内部的angle是指Spinner对象的angle属性。

您可能希望微调器返回新的角度值,然后使用微调器的英雄对象应保存返回的新角度值。

class Spinner {

  constructor(direction){
    this.direction = direction;
  }

  spin(direction, angle) {
    switch (direction) {
      case 'left':
        angle -= 1;
        break;
      case 'right':
        angle += 1;
        break;
        // no default
    }

    return angle;
  }
}

class Hero {

  constructor(xPosition, yPosition) {
    this.description = 'hero';
    this.width = 25;
    this.height = 50;
    this.xPosition = xPosition;
    this.yPosition = yPosition;
    this.angle = 0;
    this.color = 'red';
    this.spinner = new Spinner();
  }

  spin(direction) {
    this.angle = this.spinner.spin(direction, this.angle);
  }

}

const heroClass = new Hero(100, 200);

console.log(heroClass.angle); // result is 0
heroClass.spin('left');
console.log(heroClass.angle); // result is -1

我必须进行一些其他小的更改才能使其正常工作。 例如,您有一个名为“ spin”的数据属性this.spin = new Spinner以及一个名为spin spin() { 他们彼此压倒。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM