473,471 Members | 4,629 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

parenthesis around function definition

In excellent YAHOO user interface programs I see often extra parenthesis
like this

(foo=function(){
alert('I am foo');
})();

instead of

bar=function(){
alert('I am bar');
}();

Is there a reason for this? Is there a difference?

Jan 31 '07 #1
8 2804
optimistx a écrit :
In excellent YAHOO user interface programs I see often extra parenthesis
like this

(foo=function(){
alert('I am foo');
})();

instead of

bar=function(){
alert('I am bar');
}();

Is there a reason for this? Is there a difference?
AFAICT, the first one will create a function, bind it to the name 'foo',
and call it, while the second will create an anonymous function, call
it, and bind the return value of this call to the name 'bar'. But I'm
not a javascript guru, so I may be wrong...

Jan 31 '07 #2
optimistx wrote:
In excellent YAHOO user interface programs I see often extra parenthesis
like this

(foo=function(){
alert('I am foo');
})();

instead of

bar=function(){
alert('I am bar');
}();

Is there a reason for this? Is there a difference?
There is no advantage to the first form. I suspect that it was written by
someone who had seen

(function () {
alert('I am anonymous');
})();

and copied the pattern without understanding it. In this case, the parens are
required to disambiguate the function expression from the function statement.

http://javascript.crockford.com/
Jan 31 '07 #3
Douglas Crockford wrote:
....
.. I suspect that it was
written by someone who had seen

(function () {
alert('I am anonymous');
})();

and copied the pattern without understanding it. In this case, the
parens are required to disambiguate the function expression from the
function statement.

http://javascript.crockford.com/
Your suspicion is extremely accurate and correct.
Jan 31 '07 #4
On Jan 31, 1:20 pm, Douglas Crockford wrote:
optimistx wrote:
<snip>
>(foo=function(){
alert('I am foo');
})();
>instead of
>bar=function(){
alert('I am bar');
}();
>Is there a reason for this? Is there a difference?

There is no advantage to the first form.
It might be regarded as a shorter (and theoretically fractionally
faster) version of:-

foo = function(){ alert('I am foo');};
foo();

That is, assigning a function that you intend to call later but at a
point where you also want to call it immediately. Its less than clear
source code probably still mitigates against any advantage that may
follow form not doing that in two statements.
I suspect that it was written by
someone who had seen

(function () {
alert('I am anonymous');
})();

and copied the pattern without understanding it.
<snip>

Given that the second example assigns the undefined value to the - bar
- variable to no apparent advantage there does seem to be a failure to
understand somewhere.

Richard.

Jan 31 '07 #5
"Richard Cornford" <Ri*****@litotes.demon.co.ukwrote in message
news:11*********************@v45g2000cwv.googlegro ups.com...
On Jan 31, 1:20 pm, Douglas Crockford wrote:
>optimistx wrote:
<snip>
>>(foo=function(){
alert('I am foo');
})();
>>instead of
>>bar=function(){
alert('I am bar');
}();
>>Is there a reason for this? Is there a difference?

There is no advantage to the first form.

It might be regarded as a shorter (and theoretically fractionally
faster) version of:-

foo = function(){ alert('I am foo');};
foo();
That is what I thought (after seeing it in some of your code).
That is, assigning a function that you intend to call later but at a
point where you also want to call it immediately. Its less than clear
source code probably still mitigates against any advantage that may
follow form not doing that in two statements.
>I suspect that it was written by
someone who had seen

(function () {
alert('I am anonymous');
})();

and copied the pattern without understanding it.
<snip>

Given that the second example assigns the undefined value to the - bar
- variable to no apparent advantage there does seem to be a failure to
understand somewhere.
I am not entirely sure of its relevance, but:

http://subsimple.com/bookmarklets/ti...#Encapsulation

....explained it as a way of avoiding "void" in your code.

I also do not totally understand its real-world use either. That is, I see the code, I
realize it is supposed to do the same thing as void, but fail to see how or where you
would use it. That is just due to inexperience on my part though.

The way I *thought* it should work is for example when assigning a function to a link's
onclick event. Like:

(function blah() { document.bgColor = 'blue'; })
<a href="" onclick="blah();">turn blue</a>

Above, I thought surrounding your function with ()s made it the same as:

function blah() { document.bgColor = 'blue'; }
<a href="" onclick="blah(); return false;">turn blue</a*OR*
<a href="" onclick="void(blah());">turn blue</a>

This is not the case though. blah is undefined when I surround it with ()s. Long story
short, I do not understand the "function trick."

The only thing I *think* I understand is what I saw in your code.

var something = (function blah() { ...; return somethingAboutBlah; })(); *OR* without the
variable declaration.

It'd be nice if I could understand this more easily, but my brain does not work that way.
Yay for me.

-Lost

Jan 31 '07 #6
"-Lost" <sp****************@REMOVEMEcomcast.netwrote in message
news:e5******************************@comcast.com. ..
<a href="" onclick="void(blah());">turn blue</a>
Shite. Apparently I do not understand how void() works either.

(I swear I tested that before posting it. I must not have refreshed the last time.)

Now if only I understood why:

href="javascript:void(blah());" works, but onclick="void(blah());" does not.

-Lost
Jan 31 '07 #7
-Lost wrote:
Richard Cornford wrote:
>On Jan 31, 1:20 pm, Douglas Crockford wrote:
>>optimistx wrote:
<snip>
>>>(foo=function(){
alert('I am foo');
})();

instead of

bar=function(){
alert('I am bar');
}();

Is there a reason for this? Is there a difference?

There is no advantage to the first form.

It might be regarded as a shorter (and theoretically fractionally
faster) version of:-

foo = function(){ alert('I am foo');};
foo();

That is what I thought (after seeing it in some of your code).
>That is, assigning a function that you intend to call later
but at a point where you also want to call it immediately.
Its less than clear source code probably still mitigates
against any advantage that may follow form not doing that in
two statements.
>>I suspect that it was written by
someone who had seen

(function () {
alert('I am anonymous');
})();

and copied the pattern without understanding it.
<snip>

Given that the second example assigns the undefined value to
the - bar - variable to no apparent advantage there does seem
to be a failure to understand somewhere.

I am not entirely sure of its relevance, but:

http://subsimple.com/bookmarklets/ti...#Encapsulation

...explained it as a way of avoiding "void" in your code.
The context of that 'explanation' is the writing of bookmarklets. It
should not be taken as saying anything much for the general context of
javascript authoring (and would be seriously misleading if read in that
way).
I also do not totally understand its real-world use either.
There is virtually zero "real-world" use for the - void - operator.
That is, I see the code, I realize it is supposed to do
the same thing as void,
The - void - operator evaluates its Expression operand and then evaluates
its expression to the undefined value. That had nothing to do with the
inline execution of function expressions (except the coincidence that if
in such an expression the function object does not explicitly return
another value it will return the undefined value by default, and so the
whole CallExpresion's value will be the undefined value returned from the
function call).
but fail to see how or where you would use it. That
is just due to inexperience on my part though.
Probably.
The way I *thought* it should work is for example when assigning a
function to a link's onclick event. Like:

(function blah() { document.bgColor = 'blue'; })
<a href="" onclick="blah();">turn blue</a>
If you are referring to your 'blah' function (which is officially
unreferenceable as wrapping it in parenthesise makes it a
FunctionExpression with optional Identifier, rather than a
FunctionDeclaration, and so the Identifier 'blah' _should_ only be a
reference to that function object from within that function), then it is
_not_ being assigned to any link's - onclick - event.

When a browser sees the value of an intrinsic event attribute in an
(x)HTML element's tag it takes that value and uses it as the body code
for a function it creates internally and assigned to corresponding
property of the Element's representation in the DOM. So given:-

onclick="blah();"

- the browser does the equivalent of:-

LinkElementRef.onclick = function(event){

blah();

};

- internally (except that in reality some do some scope chain
augmentation and the - event - parameter is not (necessarily) used in
browsers following IE's event model).

So 'blah' is not assigned to the onclick event handler of a link, it is
called from the body of the function that the browser creates and
assigned to the onclick handler for the link.
Above, I thought surrounding your function with ()s made it
the same as:

function blah() { document.bgColor = 'blue'; }
This is a FunctionDeclaration, and so the 'blah' function should be
available globally (assuming a global context for the declaration).
<a href="" onclick="blah(); return false;">turn blue</a*OR*
For which the browser does:-

LinkElementRef.onclick = function(event){

blah();

return false;

};

<a href="" onclick="void(blah());">turn blue</a>
For which the browser does:-

LinkElementRef.onclick = function(event){

void (blah());

};
In which the - void - operator is pointless because nothing is done with
the result of the - void - operation, so its value is of no significance
anyway, and the - blah - function has no return statement so its return
value is the default undefined value. The evaluation goes:-

1. Evaluate the CallExpression (call the function and use its return
value as the evaluated result of the CallExpression), the result is the
undefined value.

2. Evaluate the grouped expression (the parenthesise that surround the
CallExpression), the result is the result of the CallExpression, the
undefined value.

3. Evaluate the - void - expression, by taking the result of the grouped
expression (the undefined value), discarding it and using the undefined
value it its place.

4. Discard that value and return form the function call.
This is not the case though.
blah is undefined when I surround it with ()s.
When you put parentheses around the code you make what was a
FunctionDeclaration into a FunctionExpression (with optional Identifier),
because a FunctionDeclaration cannot appear in an Expression context and
the subject of the grouping operators must be an Expression. However, if
you had tried that in IE the result of the well-known bug may have been
to mislead you into believing that you could still reference 'blah'.
Long story short, I do not understand the "function trick."
Trying to book mark let related 'explanations' to the general javascript
context will not be useful.
The only thing I *think* I understand is what I saw in your code.

var something = (function blah() { ...; return
somethingAboutBlah; })();
*OR* without the variable declaration.
You have never seen that in my code. I would not use the optional
Identifier with a FunctionExpression (at all, but particularly with a
function that may as well be anonymous).
It'd be nice if I could understand this more easily, but
my brain does not work that way. Yay for me.
All computer programming is the application of mechanical logic.
Everything involved can be precisely understood, in every detail, by
anyone rational, given time.

Richard.

Feb 3 '07 #8
"Richard Cornford" <Ri*****@litotes.demon.co.ukwrote in message
news:eq*******************@news.demon.co.uk...
-Lost wrote:
>Richard Cornford wrote:
>>On Jan 31, 1:20 pm, Douglas Crockford wrote:
optimistx wrote:
<snip>
(foo=function(){
alert('I am foo');
})();

instead of

bar=function(){
alert('I am bar');
}();

Is there a reason for this? Is there a difference?

There is no advantage to the first form.

It might be regarded as a shorter (and theoretically fractionally
faster) version of:-

foo = function(){ alert('I am foo');};
foo();

That is what I thought (after seeing it in some of your code).
>>That is, assigning a function that you intend to call later
but at a point where you also want to call it immediately.
Its less than clear source code probably still mitigates
against any advantage that may follow form not doing that in
two statements.

I suspect that it was written by
someone who had seen

(function () {
alert('I am anonymous');
})();

and copied the pattern without understanding it.
<snip>

Given that the second example assigns the undefined value to
the - bar - variable to no apparent advantage there does seem
to be a failure to understand somewhere.

I am not entirely sure of its relevance, but:

http://subsimple.com/bookmarklets/ti...#Encapsulation

...explained it as a way of avoiding "void" in your code.

The context of that 'explanation' is the writing of bookmarklets. It should not be taken
as saying anything much for the general context of javascript authoring (and would be
seriously misleading if read in that way).
Duly noted. Thank you.
>I also do not totally understand its real-world use either.

There is virtually zero "real-world" use for the - void - operator.
>That is, I see the code, I realize it is supposed to do
the same thing as void,

The - void - operator evaluates its Expression operand and then evaluates its expression
to the undefined value. That had nothing to do with the inline execution of function
expressions (except the coincidence that if in such an expression the function object
does not explicitly return another value it will return the undefined value by default,
and so the whole CallExpresion's value will be the undefined value returned from the
function call).
>but fail to see how or where you would use it. That
is just due to inexperience on my part though.

Probably.
>The way I *thought* it should work is for example when assigning a
function to a link's onclick event. Like:

(function blah() { document.bgColor = 'blue'; })
<a href="" onclick="blah();">turn blue</a>

If you are referring to your 'blah' function (which is officially unreferenceable as
wrapping it in parenthesise makes it a FunctionExpression with optional Identifier,
rather than a FunctionDeclaration, and so the Identifier 'blah' _should_ only be a
reference to that function object from within that function), then it is _not_ being
assigned to any link's - onclick - event.

When a browser sees the value of an intrinsic event attribute in an (x)HTML element's
tag it takes that value and uses it as the body code for a function it creates
internally and assigned to corresponding property of the Element's representation in the
DOM. So given:-

onclick="blah();"

- the browser does the equivalent of:-

LinkElementRef.onclick = function(event){

blah();

};

- internally (except that in reality some do some scope chain augmentation and the -
event - parameter is not (necessarily) used in browsers following IE's event model).

So 'blah' is not assigned to the onclick event handler of a link, it is called from the
body of the function that the browser creates and assigned to the onclick handler for
the link.
>Above, I thought surrounding your function with ()s made it
the same as:

function blah() { document.bgColor = 'blue'; }

This is a FunctionDeclaration, and so the 'blah' function should be available globally
(assuming a global context for the declaration).
><a href="" onclick="blah(); return false;">turn blue</a*OR*

For which the browser does:-

LinkElementRef.onclick = function(event){

blah();

return false;

};

><a href="" onclick="void(blah());">turn blue</a>

For which the browser does:-

LinkElementRef.onclick = function(event){

void (blah());

};
In which the - void - operator is pointless because nothing is done with the result of
the - void - operation, so its value is of no significance anyway, and the - blah -
function has no return statement so its return value is the default undefined value. The
evaluation goes:-

1. Evaluate the CallExpression (call the function and use its return value as the
evaluated result of the CallExpression), the result is the undefined value.

2. Evaluate the grouped expression (the parenthesise that surround the CallExpression),
the result is the result of the CallExpression, the undefined value.

3. Evaluate the - void - expression, by taking the result of the grouped expression (the
undefined value), discarding it and using the undefined value it its place.

4. Discard that value and return form the function call.
>This is not the case though.
blah is undefined when I surround it with ()s.

When you put parentheses around the code you make what was a FunctionDeclaration into a
FunctionExpression (with optional Identifier), because a FunctionDeclaration cannot
appear in an Expression context and the subject of the grouping operators must be an
Expression. However, if you had tried that in IE the result of the well-known bug may
have been to mislead you into believing that you could still reference 'blah'.
>Long story short, I do not understand the "function trick."

Trying to book mark let related 'explanations' to the general javascript context will
not be useful.
Again, duly noted.
>The only thing I *think* I understand is what I saw in your code.

var something = (function blah() { ...; return somethingAboutBlah; })();
*OR* without the variable declaration.

You have never seen that in my code. I would not use the optional Identifier with a
FunctionExpression (at all, but particularly with a function that may as well be
anonymous).
Ah, dangit. You are indeed correct. Your code does *not* contain the optional
identifier, but is instead, anonymous.
>It'd be nice if I could understand this more easily, but
my brain does not work that way. Yay for me.

All computer programming is the application of mechanical logic. Everything involved can
be precisely understood, in every detail, by anyone rational, given time.
Thanks for the vote of confidence. Despite how difficult that may be, I will aspire to be
just that. (Although I could not help but chuckle just a bit thinking I will aspire... on
my good days.)

Thanks again for all the information.

Be well.

-Lost
Feb 4 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Deniz Bahar | last post by:
The top level of C's precedence table has () next to , I was wondering what the () refers to. Some tables say in a footnote that () is for function calls not parenthesis, other tables say the...
38
by: Steve Kirsch | last post by:
I need a simple function that can match the number of beginning and ending parenthesis in an expression. Here's a sample expression: ( ( "john" ) and ( "jane" ) and ( "joe" ) ) Does .NET have...
2
by: Peter Fuller | last post by:
does .net have a class that will put parenthesis around negative percent?
5
by: effbiae | last post by:
hi, this code: #define M(a,b) static int is={a,b; M(1,(2,3)}) produces this (using gcc -E): static int is={1,(2,3)};
28
by: Howard Bryce | last post by:
I have come across code containing things like sizeof int How come that one can invoke sizeof without any parentheses surrounding its argument? Is this admissible within the standard? Can it...
7
by: Laurent Pointal | last post by:
on win32] Given the following: 45 .... (<generator object at 0x00A79788>,) .... File "<stdin>", line 1 SyntaxError: invalid syntax
10
by: arnuld | last post by:
this is from Steve Summit C notes: The empty pair of parentheses indicates that our main function accepts no arguments, that is, there isn't any information which needs to be passed in when the...
2
by: nevil.4u | last post by:
when we use window.onload=onload_function we doesn't use parenthesis after the function name y please reply me about this.
14
by: gimme_this_gimme_that | last post by:
What is going on here with the dollar signs and parenthesis? $(document).ready(function(){ $("li").behavior("click",function(){ $(this).load(menu.html"); }); }); And when do you use click...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.