[英]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”事件調用的函數內部。
當您調用未在非嚴格模式下用作方法的函數時,則this
是全局對象。
生產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.