Javascript closures with two instantiation -
i trying understand closure, , playing following code.i expecting value of same across objects,as closure keeps reference variable of outer function.
function test(){ var i=10; return{ get:function(){return i;}, inc:function(){i++;} } } var test1= test(); var test2=test(); test1.get(); //outputs 10 test1.inc(); test2.get(); //outputs 10, expecting 11
is understanding of closures correct, creating closure in case? new closures, detailed explanation great. thanks.
as others have mentioned, you've created 2 closures.
the easiest way understand closures is generalisation of concept of global variables. in fact, global variables in javascript nothing more closure in global scope.
a closure mechanism body of function may reference variables in outer scope. said above, global variables nothing more closure:
var x; function x_plus_plus () { x++; // variable captured closure }
every scope allows create closure. apart global scope can create closure inside other functions. me, personally, minimum example code best illustrates closures iife defines 2 functions share variable:
var incr; var val; (function(){ var x = 0; // shared functions below var via closure incr = function(){x++}; val = function(){return x}; })(); incr(); incr(); console.log(val()); // outputs 2 because functions share x console.log(x); // syntax error - x not exist in scope
note closure happens between variable , functions declared in variable's scope. not happens between variable , function variable declare in:
function () { <─────┐ ├── not closure var foo; <───────┘ } function () { var foo; <────────────────┐ ├── closure function bar () { │ do_something(foo); <───┘ } } var x; <───────────────┐ ├── closure function y () { │ call "global variable" do_something(x); <───┘ }
side note: global variables in js bit unique because they're properties of global (window) object. in theory behave if they're instance of closure. point thinking of closures global-variable-like mechanism easiest way understand them.
Comments
Post a Comment