How do javascript functions have properties in them?

后端 未结 4 1138
萌比男神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: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.

提交回复
热议问题