开发者

How do I prevent global namepace pollution in Javascript while at the same time avoiding YUICompressor warnings?

开发者 https://www.devze.com 2023-03-23 06:17 出处:网络
I am using YUICompressor to compress my jQuery plugins. Initially I got a lot of warnings \"Try to have only one var statement and one return per function\", so I put all declarations at the top like

I am using YUICompressor to compress my jQuery plugins. Initially I got a lot of warnings "Try to have only one var statement and one return per function", so I put all declarations at the top like in the following example:

        $.fn.myWidget = function () {

            var function1, function2, function3

            function1 = function () {

                // Do stuff

            };

            function2 = function () {

                // Do stuff

            };

            // This will be a global function
            fun开发者_如何学Goction3 = function () {

                // Do stuff

            };

        };

In bigger plugins this becomes a code maintenance nightmare.

Let's say I add a function4, but I forget to add the variable declaration add the top, now I am actually creating a variable in the global window namespace. If the plugin gets used multiple times on the page the global function gets overwritten.

Right now I am running the following script to check for global namespace pollution, but I was wondering if anybody has a better solution

        for (var f in window) {
            if (window.hasOwnProperty(f)) {
                $("#debug").append(f + " " + " Type: " + typeof window[f] + "<br>");
            }
        }


I prefer to declare the functions in a map form, it removes the problem of separating the declaration from the code, ie.

$.fn.myWidget = function () {

        var a, b, c, //internal vars
         myWidget = {
            function1: function () {

            // Do stuff

            },
            function2: function () {

            // Do stuff

            },
            function3: function () {

            // Do stuff

            }
        }

        return myWidget;

    };

Why do you have a global function in your widget? Doesn't that defeat the purpose of the widget? Just put it outside the declaration of the widget. Reread the question, yeah, using this style also eliminates accidentally making a global function.

Also, the jQuery DOCs provide a lot of good advice for doing it correctly

0

精彩评论

暂无评论...
验证码 换一张
取 消