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.