簡體   English   中英

處理每個函數內部的“那個”時的奇怪JS行為

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

我在使用javascript開發時注意到了一種不尋常的行為,有人可以向我解釋一下嗎?

我有一個javascript代碼:

function MyFunction(){
   var categoryId = 'abc';
   var that = this;
   $(_elem).parent().find('[data-id]').each(function(){
   that.categoryId += $(this).data('id') + ',';
   });
   setEventsCategoryEx(categoryId, url, parentUrl);
}

應該是錯誤的,因為categoryId不是全局的,所以不應該使用“that.categoryId”來訪問它。

問題是:當執行首先進入每個方法時,輸出that.categoryId將生成“abc”(我賦給本地categoryId變量的值)。

當鼠標離開每個函數時,that.categoryId和categoryId具有不同的值:categoryId =“abc”that.categoryId =“abc +”

我不明白以下內容:它們應該是分開的變量,為什么它們以相同的值開始?

謝謝,奧斯卡

編輯:對不起,當coppying和粘貼我忘了添加函數聲明。 它位於由“onclick”事件調用的函數內部。

如果你不在函數內,則var categoryId = 'abc'window.categoryId = 'abc'具有相同的效果。

如果你不在函數內部,那么this就是window

所以你看到的是預期的行為。

有關此實例,請參閱js控制台

編輯:對不起,當coppying和粘貼我忘了添加函數聲明。 它位於由“onclick”事件調用的函數內部。

編輯后, 我無法重現問題

當您調用未在非嚴格模式下用作方法的函數時,則this是全局對象。

語言規范的第11.2.3節說:

生產CallExpression : MemberExpression * Arguments *的計算方法如下:

 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). 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM