Let's delve into a more straightforward example:
class Example {
constructor(exampleMessage) {
this.exampleMessage = exampleMessage;
}
display() {
print(this.exampleMessage);
}
}
What do you think will happen with the following code?
var message = 'hi';
var example = new Example(message);
message = 'bye';
example.display();
Based on how your code is set up, it may seem like 'bye' would be printed, but in reality, 'hi' will be displayed.
This discrepancy occurs because you are passing the value of the variable to the Example
constructor. This creates two variables referencing the same value 'hi'. When you update the first variable, the second one doesn't automatically reflect that change.
To address this issue, you could utilize a single global variable like so:
class Example {
display() {
print(message);
}
}
var message = 'experimenting';
var example = new Example();
example.display();
Alternatively, you could implement a function such as setMessage()
within the class to modify the value internally:
class Example {
constructor(exampleMessage) {
this.exampleMessage = exampleMessage;
}
display() {
print(this.exampleMessage);
}
setMessage(exampleMessage) {
this.exampleMessage = exampleMessage;
}
}