How to assign to members of a function?

79 views Asked by At

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.

4

There are 4 answers

2
ruakh On BEST ANSWER

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
1
Oybek On

Simple

function something1() {};
something1.Property = "Foo";

You can directly assign the properties to any function just like a normal object. If to say in OOP language create static properties and methods.

Edit

The same inside the function

function something1() {
     something1.AnotherProp = "Bar";
};
something1.Property = "Foo";
0
Cᴏʀʏ On

Here's how I would do it:

function something1() {
    this.field = 12;
} 

var test = new something1();

alert(test.field); // alerts "12"
test.field = 42;
alert(test.field); // alerts "42"

If you're going to treat it like a class, you need to create a new instance of it before you can access its fields.

JSFiddle

0
georg On

Am I right thinking that arguments.callee does this?

Yes it did, but now they deprecated it.

Are there any other ways to set these fields?

The official way to replace callee is to use an explicit function name, as in funcName.propertyName=.... This is however not always convenient, for example, with dynamically generated functions. To quote John Resig, we're going to miss arguments.callee, it was quite useful for specific tasks.