JQuery.each将字符串文字转换为字符串.为什么?

JQuery.each converts string literals to Strings. Why?

本文关键字:字符串 为什么 转换 文字 each JQuery      更新时间:2023-09-26

我将介绍peepcode jQuery示例(https://peepcode.com/products/jquery)我选择更新所有的依赖关系。

毫不奇怪,我遇到了一个关于javascript中字符串文字和字符串对象之间差异的问题(这里有很好的讨论:为什么有两种javascript字符串?)

我遇到的一个问题是jQuery.each将字符串文本转换为string对象,而jQueryUI方法removeClass无法正确处理这一问题。以下是修复该问题的代码片段。

我想知道jQuery.each中的错误是否是将字符串文字错误地转换为字符串对象,或者removeClass应该假设它可以获得字符串文字或字符串对象

更新:我刚刚意识到还有另一个解决方法:数组中的字符串在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;
    },

这与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. 否则,将ThisBinding设置为thisArg

这是有效的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 有任何优势