Search code examples
javascriptargumentsmemberfirst-class-functions

How to assign to members of a function?


Since functions are first class objects, it should be possible to assign to the members of them.

Am I right thinking that arguments.callee does this?

Are there any other ways to set these fields?

How is it possible to set field in first case?

function something1() {
    arguments.callee.field = 12;
} 

alert(something1.field); // will show undefined
something1();
alert(something1.filed); // will show 12

something2 = function() {
    arguments.callee.field = 12;
};

alert(something2.field); // will show undefined
something2();
alert(something2.field); // will show 12

UPDATE 1

I mean how to access members from within function when it runs.


Solution

  • You don't need to use arguments.callee to refer to a function that has a name; you can just use the name. This is naturally the case when you declare the function using the

    function name(...) { ... }
    

    syntax; but even in a function expression, you're allowed to supply a temporary name:

    (function temp_name(...) { ... })(arg);
    

    So, if you want to set the properties from inside the function, you can write:

    function something1() {
        something1.field = 12;
    } 
    
    alert(something1.field); // will show undefined
    something1();
    alert(something1.field); // will show 12
    
    something2 = function something2() { // note the second "something2"
        something2.field = 12;
    };
    
    alert(something2.field); // will show undefined
    something2();
    alert(something2.field); // will show 12