It's not a secret anymore!*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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: 2840
    
  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: 60785
    
  65

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: 2840
    
  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: 60785
    
  65

The latter.

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

Joined: Oct 01, 2001
Posts: 2840
    
  11

Cool beans, thanks!
 
Don't get me started about those stupid light bulbs.
 
subject: Strange accessors in JavaScript class definition
 
Similar Threads
Not Getting the Latest data from databases in jsp page
Disable HTML frame using Javascript
How can i get the data to a drop down box from database
struts tag autocompleter with onclick, not working
page is not shown only url is showing