Go Back   CodingForums.com > :: Client side development > JavaScript programming

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-07-2013, 12:59 PM   PM User | #1
hgs
New Coder

 
Join Date: Jan 2010
Location: Germany
Posts: 52
Thanks: 1
Thanked 2 Times in 2 Posts
hgs is on a distinguished road
anonymous functions versus named function

Hi

Is there a difference in performance or memory consumption, if i create many anonymous functions in a loop like

for (i=0;i<n;i++){
element.onchange=function(){
// some code
};
}


or doing it like


function myfunc(){
// some code
}
for(i;i<n;i==){
element.onchange=myfunc;
}


My feeling is that the second version is 'better" .
Am i Wrong ?


Regards
Heinz
hgs is offline   Reply With Quote
Old 01-07-2013, 01:19 PM   PM User | #2
VIPStephan
The fat guy next door


 
VIPStephan's Avatar
 
Join Date: Jan 2006
Location: Halle (Saale), Germany
Posts: 7,615
Thanks: 5
Thanked 865 Times in 842 Posts
VIPStephan is a jewel in the roughVIPStephan is a jewel in the roughVIPStephan is a jewel in the rough
The only difference in this case is that you can re-use the named function while the anonymous one would have to be redefined everytime (in which case the performance would suffer). However, which way to go depends on the application.
__________________
Don’t click this link!
VIPStephan is offline   Reply With Quote
Old 01-07-2013, 01:56 PM   PM User | #3
niralsoni
Regular Coder

 
Join Date: Mar 2008
Location: London
Posts: 129
Thanks: 1
Thanked 31 Times in 31 Posts
niralsoni is an unknown quantity at this point
Have you heard the term 'Carpool', which is sharing a ride by multiple persons going to same location/direction. Recollect the advantages of using carpool.

Now, consider named function as the 'Carpool' wherein multiple DOM objects are utilising/ reusing the named function, similar to multiple persons sharing a ride.

So, its better to use named function for doing the same things (or similar things) multiple times.

Hope this clarifies your doubt.

Regards,
Niral Soni
niralsoni is offline   Reply With Quote
Old 01-07-2013, 08:20 PM   PM User | #4
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,999 Times in 3,968 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
Actually, we had quite a discussion on this just last week.

Apparently, the answer depends on the browser. Although perhaps it shouldn't. The ECMAScript standard says that all identical functions can be (and should be, though the "should" is less clear) represented by a single function that is shared.

And some browsers apparently do exactly that. Meaning that, unless you used your function myfunc in some place *OTHER* than shown here, the two sets of code you showed are identical. All those supposedly separate anonymous functions will actually all be automatically rolled into one implementation by the newer and smarter browsers.

However, it does seem true that there are enough older browsers out there that do *NOT* do this that the second approach is the better one in the near future.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Old 01-07-2013, 08:53 PM   PM User | #5
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Does it make if a difference if we name the function?

Code:
for (i=0; i<n; i++) {
    element.onchange = function somename() {
    // some code 
    };
}
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
AndrewGSW is offline   Reply With Quote
Old 01-07-2013, 09:27 PM   PM User | #6
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,465
Thanks: 0
Thanked 499 Times in 491 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by AndrewGSW View Post
Does it make if a difference if we name the function?

Code:
for (i=0; i<n; i++) {
    element.onchange = function somename() {
    // some code 
    };
}
Yes, there are some browsers that don't understand named functions in assignments and so those browsers will fail to run the code.

It is best to avoid using named functions at all. Assigning anonymous functions to variables allows for far greater flexibility and can be used in many places where named functions are not permitted (such as inside an if statement).

The better version of the OP's original code is:

Code:
myfunc = function(){
 // some code
 }
 for(i;i<n;i++){
 element.onchange=myfunc;
 }
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
felgall is offline   Reply With Quote
Old 01-07-2013, 09:35 PM   PM User | #7
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,469
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Quote:
Originally Posted by AndrewGSW View Post
Does it make if a difference if we name the function?

Code:
for (i=0; i<n; i++) {
    element.onchange = function somename() {
    // some code 
    };
}
no, it's still a function expression instead of a lexical-hoisting function statement. the only place somename could be seen in a your function expression is inside the function.

named functions are easier to debug than digging through 50 different anonymous() calls in a exception stack or firebug trace.

i think for that reason alone, it's better to use named function statements.

how to spot the diff?
if the char to the left of the word function is a line-terminator or semi-colon, and there is a white-space after "function" followed by /[a-z_$]+/i before the opening paren, it's a statement.

almost always, the chars to the left of the word function is whitespace and/or "=" in function expressions, which may or may not have an internal name.


i recommend giving even function expressions names for self-documentation, easier maintenance, and more-precise debugging information when you need it most.
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%

Last edited by rnd me; 01-07-2013 at 09:39 PM..
rnd me is offline   Reply With Quote
Old 01-07-2013, 09:39 PM   PM User | #8
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,469
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Quote:
Originally Posted by felgall View Post
Yes, there are some browsers that don't understand named functions in assignments and so those browsers will fail to run the code.
i don't see how a name or lack of name makes any difference at all to a function expression in any browser i've ever used. such a browser would not meet the spec.

can you give an example?
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%
rnd me is offline   Reply With Quote
Old 01-08-2013, 01:40 AM   PM User | #9
felgall
Master Coder

 
felgall's Avatar
 
Join Date: Sep 2005
Location: Sydney, Australia
Posts: 5,465
Thanks: 0
Thanked 499 Times in 491 Posts
felgall is a jewel in the roughfelgall is a jewel in the roughfelgall is a jewel in the rough
Quote:
Originally Posted by rnd me View Post
i don't see how a name or lack of name makes any difference at all to a function expression in any browser i've ever used. such a browser would not meet the spec.

can you give an example?
Three examples:

Named functions cannot be used in expressions in IE8. You can either use a named function outside an expression or an anonymous function inside an expression in that browser but cannot give the function a name and assign it in the same statement and have it run in that browser. IE8 runs jScript rather than JavaScript and so isn't required to comply with the JavaScript spec as it complies with the jScript spec which doesn't allow named functions in expressions.

Self executing named functions do not work in IE8 or Safari 2.

You cannot return a named function in IE8 or Safari 2.
__________________
Stephen
Learn Modern JavaScript - http://javascriptexample.net/
Helping others to solve their computer problem at http://www.felgall.com/
felgall is offline   Reply With Quote
Old 01-08-2013, 01:45 AM   PM User | #10
AndrewGSW
Senior Coder

 
Join Date: Apr 2011
Location: London, England
Posts: 2,120
Thanks: 15
Thanked 354 Times in 353 Posts
AndrewGSW will become famous soon enough
Quote:
almost always, the chars to the left of the word function is whitespace and/or "=" in function expressions, which may or may not have an internal name.
Just to mention other possibilities though:

Code:
something = (function () {
    // immediately invoked function expression (IIFE)
})();

get: function (arg) {
// attribute (method) assignment.
__________________
"I'm here to save your life. But if I'm going to do that, I'll need total uninanonynymity." Me Myself & Irene.
Validate your HTML and CSS
AndrewGSW is offline   Reply With Quote
Old 01-08-2013, 07:09 AM   PM User | #11
rnd me
Senior Coder

 
rnd me's Avatar
 
Join Date: Jun 2007
Location: Urbana
Posts: 3,469
Thanks: 9
Thanked 466 Times in 450 Posts
rnd me is a jewel in the roughrnd me is a jewel in the roughrnd me is a jewel in the rough
Quote:
Originally Posted by felgall View Post
Named functions cannot be used in expressions in IE8. You can either use a named function outside an expression or an anonymous function inside an expression in that browser but cannot give the function a name and assign it in the same statement and have it run in that browser. IE8 runs jScript rather than JavaScript and so isn't required to comply with the JavaScript spec as it complies with the jScript spec which doesn't allow named functions in expressions.
Code:
var sum=function SUM(x,y){return x+y;};
alert(sum(4,5)==9)


Quote:
Originally Posted by felgall View Post
Self executing named functions do not work in IE8 or Safari 2.
Code:
(function doSum(){

  var sum=function SUM(x,y){return x+y;};
  alert(sum(4,5)==9)

}());
Quote:
Originally Posted by felgall View Post
You cannot return a named function in IE8 or Safari 2.
Code:
alert (function doSum(){
  function SUM(x,y){return x+y;};
  return SUM;
}());

all three code boxes test in IE10 as IE8, which is supposed to be jScript mode. the engine can be verified by the following test:

Code:
"v"=="\v" // true in jScript, false in ECMA5
i don't have safari2, but i doubt anyone would miss that 7 year old browser...

if indeed my tests don't pan out on a "real" copy of IE8, i'll concede the point, but from what i can tell you're wrong in all three examples.

i tested your if statement claim and both IE8(via IE10) and chrome show 3 here:

Code:
 alert ( a() );

if(function a(){return 1;}){
  function a(){return 2;}
}else{
  function a(){return 3;}
}
and both throw as expected on this code:
Code:
alert( a() );

if(function a(){return 1;}){
  var a=function a(){return 2;}
}else{
  var a=function a(){return 3;}
}
maybe i'm misunderstanding your claims.
if you can show code describing what you say won't work i'd be very interested.
i do think that basic IE8 jscript should not be walled-out by a fundamental pattern, at least not just yet.
still, i can see no evidence to support your claim, so i must shift the burden of demonstrativeness to you.
__________________
my site (updated 5/13)
STATS (2013/5) HTML5:90.2% MOB:14% IE7:0.5% IE8:8.6% IE9:9.8% IE10:10%

Last edited by rnd me; 01-08-2013 at 07:12 AM..
rnd me is offline   Reply With Quote
Old 01-08-2013, 07:10 AM   PM User | #12
Old Pedant
Supreme Master coder!

 
Old Pedant's Avatar
 
Join Date: Feb 2009
Posts: 23,248
Thanks: 59
Thanked 3,999 Times in 3,968 Posts
Old Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to allOld Pedant is a name known to all
well, yes. But attribute assignment is just "syntactic sugar".

There's no difference semantically between
Code:
var f = new Object( );
f.get = function( arg ) { ... }
and
Code:
var f = {
    get : function( arg ) { ... }
}
Just two different syntaxes for acconplishing the same semantics.

Don't get me wrong, the latter code this is very nice syntactic sugar to have available, but if it didn't exist you could live without it.
__________________
An optimist sees the glass as half full.
A pessimist sees the glass as half empty.
A realist drinks it no matter how much there is.
Old Pedant is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 06:18 PM.


Advertisement
Log in to turn off these ads.