In java, it is impossible to create a variable or a method outside the class declaration.
But in Javascript, it is quite possible. I just spent a lot of time looking for the origin of a very strange bug and ended up realizing… that I had misspelled the name of a variable somewhere in my code (apart from a class declaration), which, instead of updating this variable, was creating a new one with the wrong name in the concerned classes.
So, I wonder if there is a way in Javascript to detect the creation of new variables (or methods) in a class during the operation of the program and how to do it?
Maybe we could list the methods and variables present in the constructor and check during the execution of the program that there are no new ones?
something which could be applied in all constructors and be undone (when debugging is finished)
Inside a class block, all code is already in “strict mode”:
Meaning all variables have to be declared before usage.
Moreover inside a class, we can’t declare global variables anyways.
Therefore, if we mistype a global variable name inside a class, the code should just crash!
For regular JS files, always place “use strict” as their 1st statement, so as to force variables to be declared 1st.