Is there any difference between them ? I've been using both the ways but do not know which one does what and which is better?

function abc(){

    // Code comes here.
}

abc = function (){

    // Code comes here.
}

Is there any difference between defining these functions ? Something like i++ and ++i ?

有帮助吗?

解决方案

function abc(){

    // Code comes here.
}

Will be hoisted.

abc = function (){

    // Code comes here.
}

Will not be hoisted.

For instance if you did:

 abc(); 
 function abc() { }

The code will run as abc is hoisted to the top of the enclosing scope.

If you however did:

  abc();
  var abc = function() { }

abc is declared but has no value and therefore cannot be used.

As to which is better is more of a debate of programming style.

http://www.sitepoint.com/back-to-basics-javascript-hoisting/

其他提示

Short answer: none.

You are putting the function in the global namespace. Anyone can access this, anyone can overwrite this.

The standard more safe way to do it is wrap everything in a self calling function:

(function(){
    // put some variables, flags, constants, whatever here.
    var myVar = "one";

    // make your functions somewhere here
    var a = function(){
        // Do some stuff here

        // You can access your variables here, and they are somehow "private"
        myVar = "two";
    };


    var b = function() {

        alert('hi');
    };

    // You can make b public by doing this
    return {
        publicB: b
    };
})();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top