Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
151 views
in Technique[技术] by (71.8m points)

javascript functions are objects?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...