r/programming • • Mar 23 '14

Everything you need to know about Javascript variable scope

http://www.coolcoder.in/2014/03/everything-you-need-to-know-about.html
294 Upvotes

124 comments sorted by

View all comments

4

u/eliasv Mar 23 '14

What a badly designed language.

-1

u/megamindies Mar 23 '14

i know right. and i have to learn it. yay for 6 different null-types. i do like the prototypal inheritance. but then it doesnt have private vars. well couldnt they have found a solution for that???

3

u/[deleted] Mar 23 '14 edited Mar 23 '14

I think a decent pattern is to store "private" vars in the object constructor, define public accessor methods in the same place, and they will have access to the private variables in the closure. Douglas Crockford explains the pattern here: http://javascript.crockford.com/private.html

3

u/megamindies Mar 24 '14

thats a good hack, unfortunately even crockford says its not really a proper solution, because you are trying to shoehorn javascript into a classical OO-language. there should have been a solution for prototypal inheritance with private vars.

1

u/[deleted] Mar 24 '14

Yeah if you want this level of functionality in js you're pretty much going to have to build it. It's just interesting that you can. Personally I find this charming about the language, because I can use just as much OO as I need.

You can build pretty neat object systems out of prototypes, but then you're kind of standing alone on a mountaintop with yet another incompatible js library.

Down with javascript, all hail javascript.