简体   繁体   中英

Different type of function declaration in javascript

1)Below is Function declaration with variable name

var x = function (a, b) {return a * b};

2)Below is another type of function in javascript in angular1

  var method = {
            add_category: function(data, success, failure) {
                $upload.upload({
                    url: baseUrl() + 'add_category',
                    data: data
                }).success(success).error(failure);
            },
fileupload: function(data, success, failure) 
            {   

                $upload.upload({
                    url: baseUrl() + 'ImageUpload',
                    data: data
                }).success(success).error(failure);
            }
 return method;
}

What is the difference between on both the code? first method values assign into one variable like this(var x = function (a, b)) (option 1) how second code(option 2) will works with semicolon like this(fileupload: function(data, success, failure))? how data will assign in fileupload variable?

In JavaScript, a function is a first class citizen , exactly like a string, a number or a object. Thus it can be assigned to a variable, and used everywhere a variable is expected.

This notation:

var obj = {
    item1: 10,
    item2: "string",
    item3: function (a,b) { return a*b; }
}

defines an object with three properties : a number, a string and a function. This is equivalent to:

var fn = function (a,b) { return a*b; };

var obj = {
    item1: 10,
    item2: "string",
    item3: fn
}

and you call it like this:

var prod = obj.item3(2,4); // returns 8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM