开发者

JavaScript function formats

I've seen JavaScript files formatted two different ways and I have no idea what the differences are.

<script>

function foo () { /* a function 开发者_运维技巧*/ }

</script>

name = { 

foo: function () { /* a function */ }
foo2: function () { /* a different function */ }
}

What is the difference between these two ways of writing JavaScript, and why would I do one verese the other.


The second method creates the functions as members of the object name. This has the effect of encapsulating them inside name, rather than creating them inside the global namespace. JavaScript can be very problematic in terms of variable and function naming, due to the way it utilizes the global namespace. For example, forgetting to use the var keyword when declaring a variable inside a function will cause the variable to have global scope instead of function scope.

So, that second method allows you to create just one variable at the global level, and use it as a container for several more variables and functions without worry of colliding with other global function & variable names.

A common pattern you'll see (and recommended in Douglas Crockford's Javascript: The Good Parts):

var myApplication = {
  var1: 'some variable';
  var2: 'some other variable';
  var3: 12345

  foo1: function() {
    // do something
  },
  foo2: function() {
    // do something else
  }
};

In effect, the only global variable I have created here is myApplication, and that is unlikely to cause a name collision with anything else in the global namespace. I can call my functions like:

myApplication.foo1();
myApplication.foo2();


The second form is called a namespace.

It let you define function and varibales inside it.

Think of it as a Class in java,

You can declare methods and attributes that are only accessible thru your namespace.

In your example, it let you define 2 function called foo.

One being global (the first one) One being inside an object called name (the second one)

if you want to call the second one somewhere, you must provide the namespace ex:

name.foo()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜