quick one today.
Let’s say you like the constructor pattern for objects. You probably do something similar to this:
Let’s say you forget to use the”new” operator to instantiate the function and instead just call it as is while trying to assign it to a variable:
The problem is “this”. Without referring to the “new” keyword, the function’s “this” refers to the global “this”. When you call the function, it can collide with any other variable in the global scope.
Of course you can fix it by doing:
Of course, this is the right way to do it. But how can you make sure that even if the user doesn’t call it correctly, your class doesn’t create crazy collisions and potentially cause someone to spend hours debugging?
Easy! Check your object scope. Figure out who you belong to and force instantiation otherwise:
Now your object will return an instance of itself, even if called the wrong way.