JavaScript function declaration

前端 未结 8 796
别那么骄傲
别那么骄傲 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 04:58

    There are six ways/contexts in which to create functions:

    1) Standard declarative notation (most familiar to people with C background)

    function foo() {}
    

    All the rest are function expressions:

    2) As a method of an object literal

    var obj = {
        foo: function() {}
    };
    

    3) As a method of an instantiated object (created each time new is exectued)

    var Obj = function() {
        this.foo = function() {};
    };
    

    4) As a method of a prototype (created only once, regardless of how many times new is executed)

    var Obj = function() {};
    Obj.prototype.foo = function() {};
    

    5) As an anonymous function with a reference (same effect as #1) *

    var foo = function() {};
    

    6) As an immediately executed anonymous function (completely anonymous)

    (function() {})();
    

    * When I look at this statement, I consider the result. As such, I don't really consider these as anonymous, because a reference is immediately created to the function and is therefore no longer anonymous. But it's all the same to most people.

提交回复
热议问题