I’ve simulated a static class variable in Javascript.
MyObject.staticVariable = "hello world";
function MyObject() {
// do something
}
MyObject.prototype.someFunction = function() ...
I do not understand why this syntax works because I do not create MyObject explicitly (and how could I and still have a MyObject function?) before I assign the staticVariable property. But it does work, and I’ve seen it in many answers to the question along the lines of: how do I simulate a static class variable in Javascript?
How can I achieve this functionality when I declare the MyObject function in a namespace?
var Namespace = {};
// Not allowed, and for good reason in my eyes, as NameSpace.MyObject does not exist
Namespace.MyObject.staticVariable = "hello world";
Namespace.MyObject = function() {
// do something
}
Namespace.MyObject.prototype.someFunction = function() ...
Let me know if I can clarify and/or if my thinking is off. Thanks.
Function declarations are “hoisted” to the top of the current lexical environment.
This means that the function exists before any other code in that environment runs.
In your
Namespaceexample, it’s effectively the same as the second example. This means that you’ll needs to make sure the function assignment happens first.