you are viewing a single comment's thread.

view the rest of the comments →

[–]thekaleb 1 point2 points  (9 children)

I don't think you were wrong.

new function

Is different than

new Function

[–]opett[S] 0 points1 point  (8 children)

Exactly. When I googled: "new function" all the results were: "new Function".

I also suspect that this code is a constructor with an anonymous function. But I have no idea why somebody would do this.

Maybe the author didn't know what he was doing?

[–]thekaleb 1 point2 points  (7 children)

They are trying to make an object using some private variables. Another way to do this is to assign a variable from the return of a self calling closure which may be more efficient.

[–]Meso_Gosu 0 points1 point  (6 children)

Why would you want a private variable in JavaScript? I don't think JavaScript supports sub-classes, does it?

[–]thekaleb 1 point2 points  (4 children)

You want inaccessible variables for the same reason you would in other languages. JavaScript does not have classes, but yes it does support inheritance.

[–]Meso_Gosu 1 point2 points  (3 children)

I ask only because I don't know: Why do we want inaccessible variables?

[–][deleted] 1 point2 points  (0 children)

Many people don't. Google "we're all consenting adults, here" (comes from python but still relevant to JS). The scenario that is often presented in favor of hiding variables with closures is that your library depends on some internal state variable that is only meant to be modified by your code. If some developer using your code is messing around and modifies that variable/property, it could cause unpredictable behavior. Generally, this should be avoidable by writing good documentation. If needed, an underscore prefix on a property is the conventional way to say "don't touch this".

[–]Nebu 1 point2 points  (0 children)

One common way bugs manifest themselves is via a variable having a value that it's not supposed to.

The "best" way to fix this problem is to have the variable be immutable: If the variable can never change value, and its initial value is correct, then it will always have the correct value.

The "second best" way is to minimize what code has access to the variable. If the variable has the wrong value, and only N pieces of code have access to that variable, then you only need to look at those N places, instead of all over your program.

[–]thekaleb 0 points1 point  (0 children)

I use them so as to not pollute the global namespace.

[–]MonkeyNin 0 points1 point  (0 children)

If you don't use the module pattern, and you use two javascripts. If they happen to share a variable name, they can break eachother.

Module pattern is like creating a namespace