Is it true that every function in JavaScript is a closure? -
i understand every function in javascript first-class object , has internal property [[scope]] hosts binding records of function's free variables. however, there 2 special cases.
is function created function constructor closure? function object created function constructor special, because [[scope]] may not refer lexical environments of outer functions, global context. example,
var = 1; var fn = (function outer() { var = 2; var inner = new function('alert(a); '); return inner; })(); fn(); // alert 1, not 2.
this unintuitive. called closure?
if inner function doesn't have free variables, can closure formed when inner function created? example,
// useless case academic study var fn = (function outer() { var localvar1 = 1, localvar2 = 2; return function() {}; })();
in case, fn refers empty function object created inner function. has no free variables. in case can closure formed?
is function created function constructor closure?
yes, closes on global scope. might unintuitive because other javascript closures close on lexical scope, still matches our definition of closure. in example, a
free variable, , resolves a
in other scope when inner
/fn
function called somewhere.
if inner function doesn't have free variables, can still call closure?
depends on whom ask. some yes, others call them "uninteresting closures", no because they don't reference outer scope.
Comments
Post a Comment