javascript - Scoping of params in callbacks with closure -
i know there have been many questions asked on topic interested in difference between 2 particular scenarios. here is
scenario 1
//global scope var a=1, b =2; var callbackfn = function(param3,param4){ alert(a); //1 -->defined alert(b); //2 -->defined alert(param1); //3 -->? alert(param2); //4 -->? alert(param3); //5 -->defined alert(param4); //6 -->defined alert(localvariable); //7 -->? } var classobj = { somememberfunction: function(param1, param2{ var localvariable; return $.asynccallfn(param1, param2).then(function(){ callbackfn(3,4); }); } }; classobj.somememberfunction(5,6); scenario 2
//global scope var a=1, b =2; var classobj = { somememberfunction: function(param1, param2){ var localvariable; $.asynccallfn(param1, param2).then(function(param3,param4){ alert(a); //1 -->? alert(b); //2 -->? alert(param1); //3 -->? alert(param2); //4 -->? alert(param3); //5 -->? alert(param4); //6 -->? alert(localvariable); //7 -->? }); }; } classobj.somememberfunction(5,6); what outputs of alerts #1 through #6 , more importantly there difference in scenario 1 , scenario 2.
from understanding in scenario 1 callbackfn know nothing param1, param2 , localvariable because not created inside somememberfunction. scenario 2, should somememberfunction not aware of param1, param2 , localvariable well, because closure inside somememberfunction?
thanks
javascript has lexical scope. therefore function (closure) has access variables visible in scope defined in.
example 1
// global scope // foo visible in global scope var foo = 42; // bar defined in global scope, hence can access foo function bar() { console.log(foo); } example 2
// global scope // foo visible in global scope var foo = 42; // bar defined in global scope, hence can access foo function bar(baz) { // baz defined in local scope of bar // innerfunction defined in local scope of bar // hence has access baz , foo function innerfunction() { console.log(foo, baz); } } applied example:
in scenario 1, callbackfn defined in scope (global) a, b , classobj (and callbackfn itself) defined. hence inside callbackfn, a, b, classobj, param3 , param4 accessible.
in scenario 2, callback function defined in scope (somememberfunction) a, b, classobj visible , param1 , param2 defined. hence inside callback, a, b, classobj, param1, param2, param3 , param4 accessible.
Comments
Post a Comment