【问题标题】:How to structure a javascript class to use multiple sub-methods at once?如何构造一个javascript类以一次使用多个子方法?
【发布时间】:2017-06-25 18:43:38
【问题描述】:

假设我有这三个类:

function Basket() {
   this.catches = []
}

Basket.prototype.addCatch = function(catch) {
   catches.push(catch)
}


function Pole() {
}

Pole.prototype.catchFish = function() {
   return "fish"
} 


function Fisherman() {
   this.pole = new Pole()
   this.basket = new Basket()
}

现在,当我创建 Fisherman 时,我可以钓到一条鱼并将其放入篮子中。

现在我想在一个电话中完成这两项工作。我现在实现的方式如下:

function Fisherman() {
   this.pole = new Pole()
   this.basket = new Basket()

   this.utils = {}
   this.utils.catchAndStore = function() {
      let { pole, basket } = this
      basket.addCatch(pole.catchFish())
   }.bind(this)
}

我似乎在工作,但感觉不太对劲。什么是构建我的班级以实现这一目标的好方法?还是应该从这个类中排除这种复杂性?

【问题讨论】:

  • 这是什么意思?正如您的代码一样,没有办法在“一次调用”中真正做到这一点,因为 JavaScript 引擎是单线程的、运行到完成的野兽。无论你创造什么样的“技巧”——它都会是上述的某种变体
  • What's the utils thing good for? 只需将函数放在Fisherman.prototype.catchAndStore 上,就像在其他类中的方法一样。
  • 另外,确认你不能使用ES6 classes....
  • @Bergi 我不想污染那个命名空间,这就是为什么我想把这些助手放在他们自己的对象中
  • @ThibautSchaeffer 没有污染,捕捞和储存鱼是渔夫所做的。不,当您将代码放在不同的对象上时,该代码不起作用,请参阅我的链接。如果您坚持,请使用命名约定,例如 Fisherman.prototype.util_catchAndStore

标签: javascript node.js class oop object


【解决方案1】:

就像这样:

Fisherman.prototype.catchFish = function () {
    if (!this.basket.addCatch || !this.pole.catchFish)
        return console.log("Hey!I need correct tools!");
    this.basket.addCatch(this.pole.catchFish());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-17
    • 1970-01-01
    • 2013-10-10
    • 2023-03-31
    相关资源
    最近更新 更多