开发者

greasemonkey sandbox and scope question

I am creating a GM script and had a question about how to set it up with as little global pollution as possible.

I have 1 main function which is available and a bunch of private function inside the main one. Something like this:

function main(a, b, c) {
    /* CODE */
    f1(a);
    /* CODE */
    f2(a + c);
    ...
    function f1(a) {
        /* CODE */
    }
    function f2(a) {
        /* CODE */
    }
}

I was wond开发者_运维技巧ering should I rather use var f1 = function(a) {...} or the way I have it?

Also should I use function main(a, b, c) or var main = function(a, b, c)

The only difference between the two that I can think of is if it will be parsed before running any code so I can write my code with my private functions out of the way. Are there any chanced of name conflicts either way?


I was wondering should I rather use var f1 = function(a) {...} or the way I have it?

The way you have it, function f1(){}, because then the function will have a name f1 which is useful for debugging code.

Also should I use function main(a, b, c) or var main = function(a, b, c)

you should use the name main if you plan to let other scripts use your script. The former method is better tho for the reason I gave above.

Maybe you want something like:

(function(){
   function f1() {} ;
   function f2() {};
})()


It shouldn't matter between the two ways. Any name conflicts would likely arise either way. If you do var f1 = function(a) {} you'll need to define those at the top of your main function, before you try to call them.

var main = function(a, b, c) {
    var f1 = function(a) {
        /* CODE */
    };
    var f2 = function(a) {
        /* CODE */
    };
    /* CODE */
    f1(a);
    /* CODE */
    f2(a + c);
};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜