How do javascript functions have properties in them?

后端 未结 4 1137
萌比男神i
萌比男神i 2021-01-21 09:08
function myFunc(){
    console.log(myFunc.message);
}
myFunc.message = \"Hi John\";

myFunc();

Executing the above results in -

Answer:         


        
相关标签:
4条回答
  • 2021-01-21 09:30

    How does the above work? Is function in javascript internally an object?

    Yes

    function example() {};
    
    console.log(example instanceof Object);

    0 讨论(0)
  • 2021-01-21 09:35

    Yep, they are objects.

    See in particular:

    Every JavaScript function is actually a Function object. This can be seen with the code (function(){}).constructor === Function which returns true.

    0 讨论(0)
  • 2021-01-21 09:35

    In JavaScript functions are first class objects. This is evidenced by the fact you can assign a function to a variable, pass it as an argument, add properties to it, add it as a property or member of an array etc etc. Sky is the limit.

    var myFunction = function(passedFunction){
            passedFunction();
            console.log(myFunction.message);
       };
    	 
    let functionsArray = [myFunction, function() {
           myFunction.message = "Hello World";
    }];
    	 
    functionsArray[0](functionsArray[1]);

    The above outputs "Hello World"

    Part of the reason this can seem weird may be in the way functions can be declared. In order to behave a bit like C (but not really) or other languages where a function is in some manner defined prior to the execution of the code proper, the naked 'function' statement 'hoists' the function declaration. So where you use this syntax:

    myFunction();
    function myFunction(){ 
        console.log("Hello world");
    }
    

    What is actually happening is that your function declaration is being 'hoisted' to act as if it was this:

    let myFunction = function(){ 
        console.log("Hello world");
    }
    
    myFunction();
    

    These two code snippets above are fundamentally equivalent in JavaScript. (N.b. var declarations are also hoisted but let and const are not)

    MDN has more about the function declaration and function hoisting.

    0 讨论(0)
  • 2021-01-21 09:37

    According to MDN, definition of function is:

    In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

    So here by doing myFunc.message you are adding an additional property to myFunc function( or object) and then it is accessible inside function like other objects.

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