javascript functions are objects?

后端 未结 8 2102
太阳男子
太阳男子 2020-12-14 23:10

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 wh

相关标签:
8条回答
  • 2020-12-14 23:27

    Basically, everything in Javascript is an object. If you said

    var a=3;
    a['n']=4;
    

    references to 'a' would still return 3, but a also has a member 'n' which has value 4. So when you say addn['n'] = 3 you are adding a new member to addn, and not affecting the function in any way.

    I strongly recommmend reading How good c habits can encourage bad javascript habits. In describing all the things you can do wrong, it's a great intro to the way objects work in Javascript.

    0 讨论(0)
  • 2020-12-14 23:28

    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
    
    0 讨论(0)
  • 2020-12-14 23:36

    Since JavaScript has function scope, you can use a function to store the value of n like so:

    var addn = (function(n) {
      return function(x) {
        n += x;
        return n;
      }
    }(2);
    
    addn(3) // 5
    addn(3) // 8
    
    0 讨论(0)
  • 2020-12-14 23:41

    It's best to forget completely about the traditional OO concept of "objects" in Javascript-land, and to think instead in terms of closures. I strongly recommend reading this tutorial by John Resig, the creator of jQuery.

    0 讨论(0)
  • 2020-12-14 23:42

    First, you are not changing the function variable by doing this:

    addn['n'] = 3;

    The function you defined does not have any name (also known as "anonymous function"). You are simply assigning that function to a variable called addn. A variable does not have any property- it is simply a container (Unless the variable refers to an array). So addn['n'] returns nothing.

    As user casablanca noted, you can name your function as func and then access (and modify) its properties as func.<propertyname>.

    0 讨论(0)
  • 2020-12-14 23:49

    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

    0 讨论(0)
提交回复
热议问题