I’ve noticed an unusual behavior when developing using javascript, can someone explain that to me?
I have this a javascript code:
function MyFunction(){
var categoryId = 'abc';
var that = this;
$(_elem).parent().find('[data-id]').each(function(){
that.categoryId += $(this).data('id') + ',';
});
setEventsCategoryEx(categoryId, url, parentUrl);
}
This should be wrong, because categoryId is not global, so it should not be accessible using “that.categoryId”.
The issue is:
When the execution first enters in the each method, outputting
that.categoryId would generate “abc” (the value I assigned to the local categoryId variable).
When the mouse leaves the each function, that.categoryId and categoryId have different values:
categoryId = “abc”
that.categoryId = “abc+”
I do not understand the following: they should be separated variables, why do they start with the same value?
thanks,
Oscar
Edit: sorry, when coppying and pasting I forgot to add the function declaration. It is inside a function that is called by an “onclick” event.
If you aren’t inside a function then
var categoryId = 'abc'has the same effect aswindow.categoryId = 'abc'.If you aren’t inside a function, then
thisiswindowSo what you see is expected behaviour.
See your js console for this live example
After your edit, I can’t reproduce the problem.