First, bravo to you for testing stuff in the JS console! That's excellent. We all need to be willing to experiment and try stuff out.
It turns out that there is global variable called window
that contains a JS object literal (a dictionary) containing all the global variables, including itself.
Anyhow, the keyword this
is typically bound to window
.
Try:
When OOP code is used in the usual way, the this
keyword is bound to the object at hand, but apparently that didn't
happen in the way that you used it. Try:
But inside a constructor, this
will have the correct value, namely the object being initialized.
To allow a class to refer to its super-class. This is most
important in the constructor. The constructor
for Rectangle
needs to call the constructor
for Shape
, so it uses super
to do that.
see Shapes Example
For sure! Imagine we are using the in-memory DataStore
, which just uses the following methods:
add
get
getAll
remove
Now, we happen to know that internally, there's a dictionary,
so instead of using get
and add
to
increment a value, we decide to reach inside and do
a +=
on the dictionary. Our code works and saves us a little bit of time.
Later, the project manager decides to swap out the
in-memory DataStore
for the
cloud-based RemoteDataStore
module.
The coffeerun code breaks horribly, and the manager eventually finds the culprit: it was us and our violation of the abstraction barrier. We didn't stick to the prescribed API (the published methods) and so the project broke.
Great!