Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use function as an object inside the same function

Tags:

javascript

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.

like image 490
HILARUDEEN S ALLAUDEEN Avatar asked Jul 31 '13 10:07

HILARUDEEN S ALLAUDEEN


2 Answers

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.
like image 141
Thilo Avatar answered Nov 15 '22 17:11

Thilo


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
};
like image 37
James Allardice Avatar answered Nov 15 '22 18:11

James Allardice