Kid Diamond
Kid Diamond

Reputation: 2301

Passing in window into IIFE and other dependencies also from window

Why do some programmers pass in the global window object, which I understand is for better performance and minifying benefits, but also other dependency objects / functions from the exact same global space window but passed in through another parameter?

But then they also use functions from window that they don't pass in explicitly, like setTimeout().

(function (dependency1, dependency2, dependency3, dependency4) {
    'use strict';

    //body

    window.setTimeout(function() { // <--
        //body
    }, 1000);

    //etc.
}(window, window.document, window.AjaxRequest, window.util.padNumber)); // <--

Are there any benefits to using the top variant over the following, which basically still has access to the same dependencies?

(function (window) {
    'use strict';

    //body

    window.setTimeout(function() {
        //body
    }, 1000);

    //etc.
}(window));

Upvotes: 1

Views: 1031

Answers (2)

dsuckau
dsuckau

Reputation: 592

  1. The interpreter does not have to traverse up the scope to find the dependencies, they are just available in the current scope.
  2. Location/Namespaces of dependencies may change in future, but if you pass them in as parameters you just have to change the passed parameters, not all occurrences in your code.
  3. Minification, local variables are safe to be renamed

Upvotes: 2

Vijay
Vijay

Reputation: 3023

This is done in order to stick to OPEN/CLOSE paradigm.

the open/closed principle states "software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification"

To close the modification, you pass the dependencies as parameter. This allows a programmer to change it on the fly without worrying about no of places it is being used in the function.

Upvotes: 1

Related Questions