I write the code as follows,
function Myfunction(){
Myfunction.myvar = "somevar";
}
After I execute the function, I can able to access Myfunction.myvar
How is it working? And If I do so, What is the problem hidden in this?
If any problem, please explain context of that.
Since the function does not execute until you call it, Myfunction.myvar
is not evaluated immediately.
Once you call it, the function definition has been installed as Myfunction
, so that it can be resolved when you do call it.
Something like the following would not work:
var x = {
foo: 1,
bar: x.foo } // x does not exist yet.
How is it working?
When you declare a function in some execution context, a binding is added to the variable environment of that context. When you reference an identifier, the current variable environment is checked to see if a binding exists for that identifier.
If no binding exists, the outer variable environment is checked, and so on, back up to the global scope.
So:
// OUTER SCOPE
// Binding exists for 'example'
function example() {
// INNER SCOPE
// No binding for 'example'
// References 'example' in outer scope
example.x = 1;
}
What is the problem hidden in this?
There are none (in general... although whether it's the right solution for you depends on what you're trying to do).
You are effectively creating a "static" property of the function. As JavaScript functions are first-class you can set properties on them as you would with any other object.
Note that the behaviour is different if you have a named function expression, rather than a function declaration:
var x = function example () {
// Identifier 'example' is only in scope in here
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With