javascript functions are objects?

后端 未结 8 2103
太阳男子
太阳男子 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:51

    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

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

    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
    
    0 讨论(0)
提交回复
热议问题