javascript functions are objects?

2019-01-24 07:24发布

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.

7条回答
男人必须洒脱
2楼-- · 2019-01-24 08:17

Object properties and local variables are largely unrelated:

  • var n declares a variable that is scoped to the function it's in (i.e. it is not visible outside of that function (except via closure)).

  • addn['n'] adds a property named n to addn and is equivalent to addn.n

查看更多
登录 后发表回答