Jump to content

  • Log In with Google      Sign In   
  • Create Account


Barzai

Member Since 20 Jan 2013
Offline Last Active Yesterday, 07:36 PM
-----

Topics I've Started

Javascript Closures vs. Prototyped Objects

19 February 2013 - 02:51 PM

I've seen a lot of vague stuff about closures in javascript, usually something to the effect of, "closures are powerful, you should learn them."  So, I've done some research into closures, and there's usually a pretty fancy phrase about maintaining a lexical scope after the function call has already returned.  In practical usage, though, it looks like you end up making a thing that has data members and functions that interact with those data members.

 

But wait, data and functions for that data: isn't that just an object?  I never see anyone state that prototyped objects are powerful though, and I've never seen a job listing say that they want applicants that can prototype objects.  As a result I'm trying to get a better handle on the two, and who better to ask than you folks here on gameDev who know a lot about this sort of stuff.

 

There's a post about it here:

http://c2.com/cgi/wiki?ClosuresAndObjectsAreEquivalent

 

Some of the folks oppose closures, but, from what I can see, that opposition doesn't apply to the javascript case.  They say that it creates an overly strong link between the 2 scopes.  However, in the javascript implementation the outer scope stops existing except for in the context of the closure, so it isn't an issue there.

 

 

In any case, from what I can see, It looks like the practical differences come down to this:

 

Closure advantages

 

They are the only way I know of in javascript to actually have private data members.

Javascript is really loose, so you have to pay attention to stuff you wouldn't in other languages, like scope.  Closures let you stop focusing on scope so much, because you define it expicitly when you create the closure.

 

Prototyped object advantages

 

They're faster.  I've seen a couple of references like this one:

http://blogs.msdn.com/b/kristoffer/archive/2007/02/13/javascript-prototype-versus-closure-execution-speed.aspx

Which show that making prototypes is faster than making closures, probably just because you don't have to make new copies of all the functions each time.

 

As a result, it looks like closures are better overall if object creation speed isn't a concern, and prototypes are better if it is.  However, I'm pretty new to this, so I'm probably missing a lot.  Does this analysis look mostly correct?  Are there other elements that come into play that I haven't thought of?  Any thoughts would be aprreciated.


PARTNERS