简体   繁体   中英

Strange JS behavior when handling “that” inside an each function

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 as window.categoryId = 'abc' .

If you aren't inside a function, then this is window

So what you see is expected behaviour.

See your js console for this live example

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.

After your edit, I can't reproduce the problem .

When you call a function that is not being used as a method in non-strict mode, then this is the global object.

Section 11.2.3 of the language spec says:

The production CallExpression : MemberExpression *Arguments* is evaluated as follows:

 6. If Type(ref) is Reference, then If IsPropertyReference(ref) is true, then Let thisValue be GetBase(ref). Else, the base of ref is an Environment Record Let thisValue be the result of calling the ImplicitThisValue concrete method of GetBase(ref). 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM