0

I am unfamiliar with Javascript/Typescript environment so sorry if this is a basic question. I am trying to understand some code in our production.

Let's say I have some classes that are defined like so:

class Fruit {
    errors: string[]
    appleChecker = Apple(this);
    bananaChecker = Banana(this);

    // no constructor

    doStuffOnApples() { 
        ...
        appleChecker.check();
        return this.errors;
    }

    doStuffOnBananas() {
        ...
        bananaChecker.check();
        return this.errors;
    }
}

class Apple {
    fruitChecker: Fruit;
    constructor(fruitChecker: Fruit) {
        this.fruitChecker = fruitChecker;
    }

    check() {
        ...
        this.fruitChecker.errors.push("This apple is dirty");
    }
}

class Banana {
    fruitChecker: Fruit;
    constructor(fruitChecker: Fruit) {
        this.fruitChecker = fruitChecker;
    }

    check() {
        ...
        this.fruitChecker.errors.push("This banana is dirty");
    }
}

The above is an oversimplification, but it represents the class structure I am trying to understand. I have 2 questions about the above:

1) In the lines

appleChecker = Apple(this);
bananaChecker = Banana(this);

does this refer to the same instance of Fruit, or 2 different instances?

2) Let's say I define a single instance of Fruit, so fruitChecker = Fruit(). Then I do the following in concurrent calls

fruitChecker.doStuffOnApples(apple1);
fruitChecker.doStuffOnApples(apple2);

For example, it could be concurrent because fruitChecker.doStuffOnApples is called by an API with 2 different inputs concurrently. My question is, could the fruitChecker.errors object be shared across both calls?

Jeremy Fisher
  • 2,510
  • 7
  • 30
  • 59

1 Answers1

0

Yes, this would refer to the same fruit instance, and you could push errors from both of them.

However, as is mentioned in this question, the doStuff calls would be considered to run their parts one after the other in a single thread (potentially with other events interleaved). See also.

O.O.
  • 828
  • 8
  • 17
  • Im confused by the second link. It says messages are enqueued and run to completion. One message must finish before the next message is processed. This sounds like Javascript is synchronous. Then why do people always say that Javascript runs concurrently? – Jeremy Fisher Dec 20 '19 at 02:47
  • I am not really an expert on this, so I can't know who says it is concurrent or why; but i could imagine that they mean that it is achieving many tasks concurrently (re-rendering while fetching data for example). This can however be done without running two functions at the same time, commonly by having callbacks - for example to take care of the parts of the function to be done after a fetch completes. Then the render call can be performed after the initial bit of the fetch, while the network call is made - giving apparent concurrency while only processing one call at a time. – O.O. Dec 20 '19 at 21:20