Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Strange accessors in JavaScript class definition

 
Greg Charles
Sheriff
Posts: 2984
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I came across this function in a piece of legacy JavaScript:



Eclipse marks lines 3 and 4 as having no effect, and I'm inclined to agree. I don't speak JavaScript very well though. Am I missing something? Why are these lines here?

 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64205
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow, that's pretty awful.

They essentially take the functions defined later, whose scope does not exist outside the constructor, and assign them to properties that have scope outside the constructor. Poor, poor, poor.

It'd be better to just assign the functions as literals.

It does, however, serve as a contrived example of "hoisting", where the the functions defined inside another function can be forward-referenced.
 
Greg Charles
Sheriff
Posts: 2984
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, I thought it was awful, but as Koko once said, "Very glad to hear my opinion backed by a competent authority."

However,

Bear Bibeault wrote:
It'd be better to just assign the functions as literals.


I don't completely understand that. Are you saying that it should change to:



or just:



or something else entirely?

 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64205
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The latter.

There's no need for the superfluous named functions.
 
Greg Charles
Sheriff
Posts: 2984
12
Firefox Browser IntelliJ IDE Java Mac Ruby
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Cool beans, thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic