3

I am trying my best to aviod using variables with global scope but I am not sure the best way to achieve this, currently I have a function setSizes(), (this is run once on mousedown) which gets all the measurements and doStuff(), (this is run continually on mousemove) which uses all the sizes to perform various operations:

var sizes = {};
sizes.myWidth = 0;
sizes.myHeight = 0;
sizes.myPadding = 0;
sizes.myMargin = 0;

function setSizes(){
   //sets all sizes
}

function doStuff(){
  //does stuff with sizes
}

What is the best way to avoid this sort of code? I find myself doing it continually out of "simplicity" but I can't imagine it is the most efficient way.

3
  • NOTE: You want an object, not an object: var sizes = {};. Commented Nov 14, 2013 at 18:55
  • @RocketHazmat meant to say "you want an object, not an array" Commented Nov 14, 2013 at 19:05
  • @IngoBürk: Yes, yes I did. Oops >.< Commented Nov 14, 2013 at 19:06

2 Answers 2

1

You can put a new scope around it

(function () {
    "use strict";

    var sizes = {};
    sizes.myWidth = 0;
    // ...

    function setSizes() {
        // ...
    }

    function doStuff() {
        // ...
    }
})();

Alternatively, when possible, just pass the object as a parameter. It sort of depends on the situation what feels cleaner (to me). You have to ask yourself whether an object is relevant only for that function or for the entire scope.

You can take a look at the various module patterns, too, as they will show you techniques on how to write modular code. For example, to use a particular module with another code, you simply export one (and only one) variable as your own custom namespace:

(function (exports) {
    "use strict";

    var someVar = "I won't leak to the global space!";

    exports.yourObject = {
        someFunction: function () {
            // ...
        }
    };
})(window);

yourObject.someFunction();

This is just a very simple example, please look at more common ones for better examples.

Sign up to request clarification or add additional context in comments.

Comments

0
(function () {
    var sizes = {
        myWidth: 0,
        myHeight: 0,
        myPadding: 0
        myMargin: 0
    };

    function setSizes(){
        //sets all sizes
    }

    function doStuff(){
        //does stuff with sizes
    }
}());

This construct is a IIFE (immediately invoked function expression) and this way your formerly global function is not visible outside, but only in the scope of the IIFE. BTW you used an array where an object is better suited.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.