GeeCON Prague 2014*
The moose likes HTML, CSS and JavaScript and the fly likes Strange accessors in JavaScript class definition Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Strange accessors in JavaScript class definition" Watch "Strange accessors in JavaScript class definition" New topic
Author

Strange accessors in JavaScript class definition

Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2853
    
  11

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

Joined: Jan 10, 2002
Posts: 61315
    
  66

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.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2853
    
  11

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

Joined: Jan 10, 2002
Posts: 61315
    
  66

The latter.

There's no need for the superfluous named functions.
Greg Charles
Sheriff

Joined: Oct 01, 2001
Posts: 2853
    
  11

Cool beans, thanks!
 
GeeCON Prague 2014
 
subject: Strange accessors in JavaScript class definition