JavaScript function declaration

前端 未结 8 795
别那么骄傲
别那么骄傲 2021-01-30 04:49

Are the JavaScript code snippets given below some sort of function declaration? If not can someone please give an overview of what they are?

some_func = function         


        
相关标签:
8条回答
  • 2021-01-30 05:18

    First is local (or global) variable with assigned anonymous function.

    var some_name = function(val) {};
    some_name(42);
    

    Second is property of some object (or function with label in front of it) with assigned anonymous function.

    var obj = {
        show: function(val) {},
        // ...
    };
    obj.show(42);
    

    Functions are first-class citizens in JavaScript, so you could assign them to variables and call those functions from variable.

    You can even declare function with other name than variable which that function will be assigned to. It is handy when you want to define recursive methods, for example instead of this:

    var obj = {
        show: function(val) {
            if (val > 0) { this.show(val-1); }
            print(val);
        }
    };
    

    you could write:

    var obj = {
        show: function f(val) {
            if (val > 0) { f(val-1); }
            print(val);
        }
    };
    
    0 讨论(0)
  • 2021-01-30 05:19

    The first example creates a global variable (if a local variable of that name doesn't already exist) called some_func, and assigns a function to it, so that some_func() may be invoked.

    The second example is a function declaration inside an object. it assigns a function as the value of the show property of an object:

    var myObj = {
        propString: "abc",
        propFunction: function() { alert('test'); }
    };
    
    myObj.propFunction();
    
    0 讨论(0)
提交回复
热议问题