2012-01-09 181 views
0

我正在通過peepcode jQuery示例(https://peepcode.com/products/jquery),我選擇更新所有依賴關係。JQuery.each將字符串文字轉換爲字符串。爲什麼?

不足爲奇的是,我遇到了一個問題,關於字符串和String對象之間的JavaScript(大討論在這裏:Why are there two kinds of JavaScript strings?)的區別

一個問題我打的是jQuery.each字符串文字轉換爲字符串jQueryUI方法removeClass無法正確處理的對象。這是修復問題的代碼片段。

我想知道如果錯誤是在jQuery.each錯誤地將字符串文字轉換爲字符串對象或應該removeClass假設它可以得到一個字符串文字或字符串對象。

更新:我剛剛意識到這是另一種解決辦法: Strings in array are no longer strings after jQuery.each()

下面的代碼:

jQuery.fn.extend({ 
    taskStates:["task-empty", "task-x", "task-apostrophe", "task-dash"], 

    resetTaskStateClassNames: function() { 
     var elements = this; 
// Commented code breaks as "this" becomes the String object not the literal 
// and removeClass does not check for String Object 
//  jQuery.each(jQuery.fn.taskStates, function(){ 
//   elements.removeClass(this); // this is the taskState 
//  }) 
     jQuery.fn.taskStates.forEach(function(ts) { 
      elements.removeClass(ts); 
     }); 
     return this; 
    }, 

回答

0

這是工作的jQuery代碼片段。自從截屏製作後,我想API(http://api.jquery.com/jQuery.each/)發生了變化。

 jQuery.each(jQuery.fn.taskStates, function(index, value){ 
      elements.removeClass(value); // this is the taskState as a string literal 
     }) 

除了這個事實,你可以在任一對象的屬性或數組jQuery.each,我沒有看到過簡單地使用JavaScript的forEach

任何優勢
2

這有什麼好做的jQuery。非嚴格模式下的this的值被強制爲一個對象,就像Object(this)一樣。

http://es5.github.com/#x10.4.3

10.4.3輸入功能碼#Ⓣ

當控制進入包含在函數對象F代表功能代碼的執行上下文,提供thisArg呼叫者執行下面的步驟,和一個呼叫者提供argumentsList:

  1. 若功能碼是嚴格代碼,所述ThisBinding設定爲thisArg
  2. 不然,如果thisArgnullundefined,則ThisBinding設置爲全局對象。
  3. 不然,如果類型(thisArg)對象,設置ThisBinding到ToObject(thisArg)
  4. 其他設置ThisBindingthisArg