javascript functions are objects?
If I understand your question correctly, you can give a name to your anonymous function and access the function object's properties through that:
var addn = function func(a) {
return func.n + a;
};
addn['n'] = 3;
addn(3); // returns 6
Private variables in a function scope, and a property of an object are 2 very different things. var n
inside that function is completely inaccessible from outside that function.
So after that code runs, addn.n == 3
, but the different value set to var n
is initialized every time the funciton runs. Due to the quirks of javascript, a function can't really access it own properties very easy. Instead this pattern would be better achieved by passing in an argument function(n, a)
Or use an object to achieve something similar.
var adder = {
n: 0,
addn: function(a) {
return this.n + a;
}
};
adder.n = 5;
adder.addn(2); // 7