Method vs Functions, and other questions

前端 未结 8 1661
梦毁少年i
梦毁少年i 2020-11-27 13:26

With respect to JS, what\'s the difference between the two? I know methods are associated with objects, but am confused what\'s the purpose of functions? How does the syntax

8条回答
  •  没有蜡笔的小新
    2020-11-27 14:08

    var myFirstFunc = function(param) {
        //Do something
    };
    

    and

    function myFirstFunc(param) {
        //Do something
    };
    

    are (almost) identical. The second is (usually) just shorthand. However, as this jsfiddle (http://jsfiddle.net/cu2Sy/) shows, function myFirstFunc will cause the function to be defined as soon as the enclosing scope is entered, whereas myFirstFunc = function will only create it once execution reaches that line.

    As for methods, they have a this argument, which is the current object, so:

    var obj = {};
    obj.func = function( ) {
        // here, "this" is obj
        this.test = 2;
    }
    console.log( obj.test ); // undefined
    obj.func( );
    console.log( obj.test ); // 2
    

    The exact syntax you showed is because you can also do this:

    function abc( ) {
        this.test = 2;
    }
    var obj = {};
    obj.func = abc;
    obj.func( ); // sets obj.test to 2
    

    but you shouldn't without good reason.

提交回复
热议问题