I am struggling with a Javascript question for some time now and I was not able to find an explanation on the web. I guess it is because I do not enter the right keywords which might also be related to why I am struggling with this at all.
My basic assumption is that it is possible to alter objects:
> var x = {'n': 2};
> x['n']
2
> x['n'] = 3;
3
pheww that worked. But still (functions are objects, too):
> var addn = function(a) {
var n = 2;
return n + a;
}
> addn(3);
5
> addn['n'] = 3;
3
> addn(3);
5
This time I was not able to change 'n'. Is there a way to fix this while keeping the functional flavor? As opposed to going fully OO. A related question I have would be how to maintain dependencies of functions for the purpose of for example testing - again w/o going OO? Of cause I am looking for a solution but if possible I would also like to understand which mechanism in Javascript makes me struggling.
Cheers,
Mark
Disclaimer: By mentioning OO I do not intent to say anything against OO. And I do not intent to say anything against VI or Emacs either. If I somehow hurt your feelings please skip this one.
Every function has a scope
, basically where/how the function gets called. When a function gets called, it creates a new function execution context pushes it on the call stack; nothing in that context exists until that line/statement is read by the language, which won't happen until the function gets called.
What you were doing was assigning a value to the PROPERTY of the function, not accessing the variable n
in that scope.
You cannot access an inner scope from an outer scope because the inner scope does not exist to the outer BUT you can access an outer scope from an inner scope because the outer scope exists to the inner scope.
Also, here is a bit of an FYI.
JavaScript is prototype
based; not class
based. EVERYTHING in JavaScript is an object, even functions. Read this to learn more about why that is (it's a good post on Quora) - https://www.quora.com/Why-is-function-an-object-in-Javascript
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
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