Reputation: 43
I am confused about scope when comparing normal function and immediate function. Here is a example:
var num=5;
var x=3;
doubleNum = function(){
num = num*x
x++;
return num;
};
console.log(doubleNum());//15
console.log(doubleNum());//60
console.log(doubleNum());//300
This is a normal function that num and x are defined globally and accessible by doubleNum, as a result num and x are updated.
var num=5;
var x=3;
doubleNum = function(){
num = num*x
x++;
return num;
}();
console.log(doubleNum);//15
console.log(doubleNum);//15
console.log(doubleNum);//15
However if I define a immediate function and call it same way as above, I got different answer. Even I am expecting to have same output Did I miss something essential? Or did I understand some concept wrong? Please help. Thanks in advance. Jsfiddle
Upvotes: 0
Views: 79
Reputation: 131
The immediate function call is being evaluated only once. You're allocating a value not an immediate function to doubleNum. To accomplish a similar effect, try using a class and getters.
class ClassName {
constructor(){
this.num = 5;
this.x = 3;
}
get doubleNum() {
this.num = this.num*this.x++;
return this.num;
}
}
var double = new ClassName();
console.log(double.doubleNum);//15
console.log(double.doubleNum);//30
console.log(double.doubleNum);//300
Upvotes: 0
Reputation: 68665
Because your doubleNum
is not a reference to the function, but keeps the result of an anonymous function call.
In the first case you assign to the doubleNum
a function and every time calling it via doubleNum()
, you change the outscoped variables inside it and return a num
. You do this 3
times. Your code is equivalent something to like
var num=5;
var x=3;
doubleNum = function(){
num = num*x; // Every call will affect the outscoped num
x++; // Every call will affect the outscoped x
return num;
};
var val = doubleNum(); // Call changes the values and returs a new result
console.log(val);
val = doubleNum(); // Call changes the values and returs a new result
console.log(val);
val = doubleNum(); // Call changes the values and returs a new result
console.log(val);
In the second case you assign to the doubleNum
the result of a single call anonymous function. The function value is already computed one time and assigns the result to the doubleNum
. Your code is equivalent something to
var num=5;
var x=3;
var doubleNum;
var myFunction = function(){
num = num*x;
x++;
return num;
};
doubleNum = myFunction(); // Only one call
console.log(doubleNum);
console.log(doubleNum);
console.log(doubleNum);
Upvotes: 5
Reputation: 68413
Did I miss something essential?
Just that in the second case, the value of doubleNum
is already computed because the function is invoked as soon as it is defined.
On the other hand, in the first case only function
definition was assigned to doubleNum
rather than the result of its invocation.
Upvotes: 0