为什么这个JavaScript原型函数会破坏jQuery?

前端之家收集整理的这篇文章主要介绍了为什么这个JavaScript原型函数会破坏jQuery?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
题:

只要我将以下代码添加到我的html页面,我就得到:

Line: 4
Error: Object doesn't support the property or method "exec".

这是导致错误的原型:

Object.prototype.allKeys = function () {
        var keys = [];
        for (var key in this) 
        {
            // Very important to check for dictionary.hasOwnProperty(key) 
            // otherwise you may end up with methods from the prototype chain.. 
            if (this.hasOwnProperty(key)) 
            {
                keys.push(key);
                //alert(key);
            } // End if (dict.hasOwnProperty(key)) 

        } // Next key

        keys.sort();
        return keys;
    }; // End Extension Function allKeys

这是重现错误所需的最小代码(浏览器问题:IE9):

<!DOCTYPE html>
<html>
<head>
    <title>TestPage</title>

    <script type="text/javascript" src="jquery-1.9.1.min.js"></script>


    <script type="text/javascript">
        /*
        Object.prototype.getName111 = function () {
            var funcNameRegex = /function (.{1,})\(/;
            var results = (funcNameRegex).exec((this).constructor.toString());
            return (results && results.length > 1) ? results[1] : "";
        }; // End Function getName
        */

        Object.prototype.allKeys = function () {
            var keys = [];
            for (var key in this) 
            {
                // Very important to check for dictionary.hasOwnProperty(key) 
                // otherwise you may end up with methods from the prototype chain.. 
                if (this.hasOwnProperty(key)) 
                {
                    keys.push(key);
                    //alert(key);
                } // End if (dict.hasOwnProperty(key)) 

            } // Next key

            keys.sort();
            return keys;
        }; // End Extension Function allKeys

    </script>

</head>
<body>

    <select id="selLayers" name="myddl">
      <option value="1">One</option>
      <option value="2">Twooo</option>
      <option value="3">Three</option>
      <option value="4">Text1</option>
      <option value="5">Text2</option>
    </select>


    <script type="text/javascript">

        //var dict = { "de": { "Text1": "Ersetzung 1","Text2": "Ersetzung 2" },"fr": { "Text1": "Replacement 1","Text2": "Réplacement 2" },"it": { "Text1": "Replacemente 1","Text2": "Replacemente 2" },"en": { "Text1": "Replacement 1","Text2": "Replacement 2"} };
        /*
        var languages = dict.allKeys();


        for (var j = 0; j < languages.length; ++j) 
        {
            var strCurrentLanguage = languages[j];
            var dictReplacements = dict[strCurrentLanguage]
            var keys = dictReplacements.allKeys();

            //alert(JSON.stringify(dictReplacements));
            //alert(JSON.stringify(keys));


            for (var i = 0; i < keys.length; ++i) {
                var strKey = keys[i];
                var strReplacement = dictReplacements[strKey];

                alert(strKey + " ==> " + strReplacement);
                //alert('#selLayers option:contains("' + strKey + '")');
                //$('#selLayers option:contains("' + strKey + '")').html(strReplacement);
                //$('#selLayers option:contains("Text1")').html("foobar");


            }    
        }
        */


        $('#selLayers option:contains("Twooo")').text('Fish');


        //alert(dict.allKeys());        
        //alert(dict["de"]["abc"]);




        /*

        $('#selLayers option[value=2]').text('Fish');
        $('#selLayers option:contains("Twooo")').text('Fish');
        $('#selLayers option:contains("Twooo")').html('&Eacute;tage');
        // https://stackoverflow.com/questions/7344220/jquery-selector-contains-to-equals

        $("#list option[value=2]").text();

        $("#list option:selected").each(function () {
            alert($(this).text());
        });  

        $("#list").change(function() {
            alert($(this).find("option:selected").text()+' clicked!');
        });

        */

    </script>

</body>
</html>

我尝试重命名原型函数,以防它与任何jquery原型冲突,但这根本没有帮助.

解决方法

因为这将为每个对象添加一个可枚举项. Sizzle(jQuery使用)使用对象文字来配置它们的选择器解析.当它循环这些配置对象以获取所有令牌时,它不会期望您的功能.在这种情况下,它可能会尝试将您的函数用作RegExp.

想象一下这种情况:

var obj = { a: 1,b: 2,c: 3 };
var result = 0;
for (var prop in obj) {
  // On one of these iterations,`prop` will be "allKeys".
  // In this case,`obj[prop]` will be a function instead of a number.
  result += obj[prop] * 2;
}
console.log(result);

如果你在Object的原型中添加了任何不能用作数字的东西,那么你的结果就会得到NaN.

这个问题的一个很好的解决方案是将allKeys函数添加到Object而不是Object.prototype.这模仿Object.keys

Object.allKeys = function (obj) {
    var keys = [];
    for (var key in obj) 
    {
        // Very important to check for dictionary.hasOwnProperty(key) 
        // otherwise you may end up with methods from the prototype chain.. 
        if (obj.hasOwnProperty(key)) 
        {
            keys.push(key);
            //alert(key);
        } // End if (dict.hasOwnProperty(key)) 

    } // Next key

    keys.sort();
    return keys;
}; // End Extension Function allKeys

猜你在找的jQuery相关文章