Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
155
rated 0 times [  156] [ 1]  / answers: 1 / hits: 15738  / 8 Years ago, thu, april 21, 2016, 12:00:00

I'm coming from an Actionscript background and (very late to the party) I am trying to learn JavaScript. I am going through this AngularJS - Video Tutorial For Beginners on YouTube (it's pretty good) and saw something really basic that I don't understand.



At line 5 the var workcount is defined. Then two anonymous functions are defined and returned in an object. The functions reference workcount but isn't workcount in a different scope? Is this like blocks in Objective-C where local vars remain accessible within the block. Is there a name for what this is?



Or if a function knows about vars previously defined in its scope, would the function task2 know about task1?



It bugs me that I can't make sense of this.



Update: Thanks for all the replies. I get it now – and while I have seen the term closures before, I never understood it (it seems a not very descriptive term. In reading up, I saw the term stack-frames and then the light bulb lit up: stack... frame of reference);






var createWorker = function(){

var workCount = 0;

var task1 = function(){
workCount += 1;
console.log(task1 , workCount);
};

var task2 = function(){
workCount += 1;
console.log(task2 , workCount);
};

return {
job1: task1,
job2:task2
}
};

worker=createWorker();

worker.job1();

worker.job2();


Output:



task1 1
task2 2

More From » javascript

 Answers
0

Just note that the variable and the two anonymous functions are wrapped inside the same function (let's call it a parent function). So the scope of this variable is available within this parent function.



So now this variable acts as a global variable for these two inner functions But the scope is limited to the parent function. Both the inner functions share the same variable.. Changing the value of the variable in one function will have effect in other function too..



So taking the logic in the post Let's say we execute task1 and task2 one after the other. The variable is initially set to 0. Then in your task1 it's incremented by one. Which makes the variable value 1 (0 + 1). Now in task two also its increased by one, making its value 2 (1 + 1).



This scope concept is called as closure in JavaScript.


[#62459] Tuesday, April 19, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
yamileth

Total Points: 53
Total Questions: 96
Total Answers: 112

Location: England
Member since Tue, Sep 8, 2020
4 Years ago
;