最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript anonymous function syntax - Stack Overflow

programmeradmin4浏览0评论

What is the difference between the following two blocks?

// block 1
{
    console.log("anonymous block");
}

// block 2
(function anon() {
    console.log("anonymous block 2");
})();

I ran this in Netbeans (using the node.js plugin) and they both seem to work...

What is the difference between the following two blocks?

// block 1
{
    console.log("anonymous block");
}

// block 2
(function anon() {
    console.log("anonymous block 2");
})();

I ran this in Netbeans (using the node.js plugin) and they both seem to work...

Share Improve this question asked Sep 7, 2012 at 20:45 Jeff StoreyJeff Storey 57.3k75 gold badges243 silver badges413 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 6

The difference is that you can use the latter form to hide global variables without destroying them.

For example, suppose you're using the jQuery library, which by default aliases its main namespace to $. If you wanted to use $ for a different purpose without changing how $ is normally used, you could do something like this:

(function($) {
    // Use $ without clashing with the jQuery object.
})(someObject);

In fact, it's also useful for one other purpose. Since undefined is NOT a reserved word in JavaScript, it can be given a value and lose its purpose. So you could simply not pass a value into an undefined parameter, and you know it will behave properly without clashing with a global value.

undefined = "some not-undefined value";    // you'd have to be an idiot to do this but I've seen it done
(function(a, b, undefined) {
    console.log(typeof(undefined) === "undefined");   // true
})(someA, someB);

The first creates a block, which is not the same as a function. You can use anonymous self-executing functions to create local, private variables and return an interface from it. It's called the Module Pattern.

var Module = (function() {

    var method = function() { console.log("anonymous block"); },
        someOtherMethod = function() {};

    return { // return our interface as an object literal
        method: method,
        someOtherMethod: someOtherMethod
    };
})();

Module.method(); // "anonymous block"

We can call it, keeping the variables method and someOtherMethod isolated from the global scope. It's one of the most important, useful features of object-oriented programming in JS.

block 1 will have scope of the block it is inside, setting a var will overwrite it in the parent, you can use let.

var a = 2;
{
    var a = 4;
}
a; // === 4

block 2 will have global scope but anything set by var will be forgotten after it is executed.

var a = 2;
(function(){
    var a = 4;
})();
a; // === 2
发布评论

评论列表(0)

  1. 暂无评论