1

Let's say I have those three classes:

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()
}

Now when I create a Fisherman I can catch a fish and put it into the basket.

Now I would like to do both in one call. The way I implemented it now is the following:

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)
}

I seems to work but does not feel quite right. What would be a good way to structure my class to achieve this goal? Or should this complexity be let out of this class?

  • What does this "both in one call" mean? As your code is, there is no way to actually do that in "one call" as JavaScript engine is single-threaded, run-to-completion kind of beast. Whatever kind of "trick" you'd create - it will be some sort of variation of the above – ZenMaster Feb 08 '17 at 08:37
  • 1
    [What's the `utils` thing good for?](https://stackoverflow.com/questions/15884096/organize-prototype-javascript-while-perserving-object-reference-and-inheritance) Just put the function on `Fisherman.prototype.catchAndStore` like you did with the methods in the other classes. – Bergi Feb 08 '17 at 08:38
  • Also, verify you can't use [ES6](https://webapplog.com/es6/) classes.... – ZenMaster Feb 08 '17 at 08:39
  • @Bergi I did not want to pollute that namespace, that's why I wanted to put those helpers in their own object – Thibaut Schaeffer Feb 08 '17 at 09:08
  • @ThibautSchaeffer There's no pollution, *catching and storing fish* is what a Fisherman *does*. No, the code doesn't work when you put it on a different object, see my link. If you insist, use a naming convention such as `Fisherman.prototype.util_catchAndStore`. – Bergi Feb 08 '17 at 11:25

1 Answers1

0

just like this:

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());
}
Roscoe
  • 19
  • 2