JavaScript function declaration

前端 未结 8 803
别那么骄傲
别那么骄傲 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);
        }
    };
    

提交回复
热议问题