Reputation: 575
In this code I can't understand why if I insert a breakpoint on the first if condition in success if(data == 1){
I can see fromCTA
variable but not $form
:
jQuery('.pane-tab form, form#hlp_contactCTA').on('click','.input-submit',function(e){
var $form = jQuery(this).parent('form');
var fromCTA = false;
var formArrSerialized = $form.serializeArray();
var len = formArrSerialized.length;
for(var i=0; i<len; i++ ){
if(formArrSerialized[i].name == 'message'){
var msg = formArrSerialized[i].value;
}
}
if(msg){
if(!$form.is('#msg-form')){ //we are in user account
fromCTA = true;
//formArrSerialized.push({name:'fromCTA', value: 1});
}
formArrSerialized.push({name:'action', value:'send_message'});
var param = jQuery.param(formArrSerialized);
jQuery.ajax({
url:pathToAjax() + 'wp-admin/admin-ajax.php',
data:param,
type:'POST',
success: function(data){
if(data == 1){
if(!fromCTA){
appendMsg(msg);
} else {
showMsg('Il messaggio è stato inviato',2000,function(){jQuery('#popup-contactCTA').hide();});
}
} else {
console.log('qualcosa è andato storto');
};
},
error: function(){
console.log('error');
}
});
}
e.preventDefault();
});
The code is working fine, there are no bugs, please analyse it only to answer my question, which regards variable scope:
in anonymous function in success i can see in the Chrome debugger as a closure only the variable fromCTA
and msg
while I expected to see $form
, formArrSerialized
and len
. All of them in my opinion have the same domain
Upvotes: 0
Views: 30
Reputation: 708056
This is just the way the debugger works. By default, the debugger only shows you the variables in the current scope. It does not show you variables in a parent scope.
But, if you set up a watch point for a variable in the parent scope such as $form
, you will be able to see its value just fine.
So, this is just how the debugger works and nothing to do with how the code actually works or how Javascript actually works. This is probably done because there could be a lot of variables in the global scope and if those were all included in the list of variables in scope, it would really complicate seeing the more local variables.
Remember that scope is hierarchical. While you're asking about some variables one level up the hierarchy, there could be many more levels of scope above and then it will eventually get to the global scope which would include all global variables. So, what you're seeing is really just a UI choice made in the debugger.
Upvotes: 2