Parentheses () Outsider And After A Function - Nested Object Namespacing

It looks like:

; (function()
{ ...
})()

There are three purposes of it:

1. The function is anonymous so it can't be called the usual way. The outer brackets have to be there so that it can be called using brackets to enable the parameter feeding:

; (function(str){alert(str)}("test"))

2. Someone may to extend above-mentioned purpose to make the calling this anonymous function immediately after after the function definition, which is ofter called Self-ting Temporary Function. In this case, it is often with empty parameter.

3. Let us look at following example first:

; var myApp = {}
; myApp.message = 'hello'
; myApp.sayHello = function()
{ alert(this.message);
}
; myApp.sayHello() // works because "this" refers to myApp object.
; var importedfn = myApp.sayHello
; importedfn() // error because "this" refers to global object.

The lesson to be learned here is that this should never refer to an object being used as a namespace because it leads to confusion about importing identifiers from that namespace. People use nested object namespacing to avoid the identifier collisions. According to Peter Michaux, it is unnecessarily complex when the goal is simply avoiding identifier collisions.

Conclusion: Avoid this practice if you have other choice.


http://peter.michaux.ca/articles/javascript-namespacing
http://ejohn.org/apps/learn/

No comments:

Post a Comment

Labels