special operator about function

A

alex

<script>
var sd=function(){
return{
f1:function(){
alert('f1');
},
f2:function(){
alert('f2');
}
}
}();

sd.f2();
</script>

when execute sd.f2();it will alert f2,who can explain this?sd is a
function name? thanks so much.
 
A

alex

var sd1={

f1:function(){
alert('f1');
},
f2:function(){
alert('f2');
}
};

sd1.f2();

if i use code above,i can get the same result.could anyone explain
this?
thanks a lot!
 
R

Randy Webb

alex said the following on 12/14/2006 3:54 AM:
<script>
var sd=function(){
return{
f1:function(){
alert('f1');
},
f2:function(){
alert('f2');
}
}
}();

sd.f2();
</script>

when execute sd.f2();it will alert f2,who can explain this?sd is a
function name? thanks so much.

Change the alert in the function to alert('It didnt alert f2') and the
alert will change. It isn't alerting the function name, it is alerting
the string you told it to alert.
 
V

VK

var sd1={

f1:function(){
alert('f1');
},
f2:function(){
alert('f2');
}
};

sd1.f2();

if i use code above,i can get the same result.could anyone explain
this?
thanks a lot!

The results are different, they only seem the same.

In the first case you create an anonymous function, execute it right
away and assign the return value of this function to variable sd1.
The return value of the function is an object with properties f1 and f2
holding the references to anonymous inner functions created during the
execution.
The execution context is being kept (a closure being formed).

Sometimes the function is being put into parenthesis, it improves the
code readability but not required: () operator ("function call"
operator) has the highest precedence in JavaScript.

<script type="text/javascript">
var sd = function(){
var message = 'Hello!';
arguments = null;
return {
f1:function(){
alert('f1: ' + message);
},
f2:function(){
alert('f2: ' + message);
}
}
}();

sd.f1();
</script>

In the second case you simply create an object with properties f1 and
f2 holding the references to anonymous functions. No closure is being
formed.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top