【问题标题】:Call method whenever method in other class is called调用其他类中的方法时调用方法
【发布时间】:2017-06-25 01:15:40
【问题描述】:

在给定的两个类中:

class Person {
  constructor(name) { 
    this.name = name; 
  }

  feedCats() {
    console.log(this.name + ' fed the cats');
  }
}

和:

class Cat {
  constructor(name) {
    this.name = name;
  }

  meow() {
    console.log(this.name + ' says \'meow\'');
  }
}

我希望在Person 的任何实例调用feedCats() 方法时调用每个Cat 实例中的方法meow()。我该怎么做?

我认为可能需要事件处理,但是在 JavaScript 中使用addEventListener() 方法时需要event 类型,但我找不到合适的类型。我需要最快的 JavaScript 或 jQuery 解决方案。

【问题讨论】:

    标签: javascript jquery class oop events


    【解决方案1】:

    我相信有一个非常简单的方法可以解决这个问题。

    feedCats 移动到一个名为CatFeeder 的新类中,并添加在调用feed 之前应该喂哪些猫:

    class CatFeeder extends Person {
        constructor(...args) {
             super(...args);
    
             this.cats = [];
        }
    
        addCat(name) {
             this.cats.push(new Cat(name));
        }
    
        feed() {
             this.cats.forEach(cat => cat.meow());
    
             console.log(`${this.name} fed the cats and they said meow!`);
        }
    }
    
    
    var catFeeder = new CatFeeder("Matías");
    catFeeder.addCat("Inno");
    catFeeder.addCat("Darky");
    
    catFeeder.feed();
    

    归根结底,Person 本身并不是喂猫器,而是CatFeeder(他是个人,但不是任何人)。对我来说,这比考虑到任何人都有养猫的属性和行为要自然得多。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 2012-11-05
      • 2011-07-04
      • 1970-01-01
      相关资源
      最近更新 更多