Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript module pattern from You don't know JS

I have been reading and testing below code out for several hours now and I just can't seem to grasp certain things. I have been stepping through chrome console basically putting break in every line I can add and have been inspecting and I am just not sure of things

1)I am just not sure of the purpose of deps array. First odd thing to me is , why doesn't script try to put data on first call to it(from MyModules.define("bar",[],function()) ? Why does script make second call to define(MyModules.define("foo",["bar"], function(bar)) and then add ["bar"] to the array when first define should have done it in the first place?

2)This code modules[name] = impl.apply(impl,deps). Each callbacks, do not use 'this'.. so was apply necessary here? Also, this is probably my lack of understanding in callback when 'apply' is used, but how does one read this? I thought 'apply' typically goes functionName.apply(obj,[])

In this case, is this almost like saying functionName.apply(functionName, []) ?? Or is this different because function itself is anonymous?

    var MyModules = (function Manager() {
        var modules = {};

        function define(name,deps,impl) {
            for ( var i=0; i<deps.length; i++) {
                deps[i] = modules[deps[i]];
            }
            modules[name] = impl.apply(impl,deps);
        }

        function get(name) {
            return modules[name];
        }

        return {
            define : define,
            get: get
        };
    })();

    MyModules.define("bar",[],function() {
        function hello(who) {
            return "Let me introduce: " + who;
        }

        return {
            hello : hello
        };
    })

    MyModules.define("foo",["bar"], function(bar) {
        var hungry = "hippo";

        function awesome() {
            console.log(bar.hello(hungry).toUpperCase() );
        }

        return {
            awesome: awesome
        };
    });

    var bar = MyModules.get("bar");
    var foo = MyModules.get("foo");

    console.log(bar.hello("hippo"));

    foo.awesome();
like image 726
user3502374 Avatar asked Jul 10 '15 04:07

user3502374


People also ask

What is the module pattern in JavaScript?

The Module Pattern is one of the important patterns in JavaScript. It is a commonly used Design Pattern which is used to wrap a set of variables and functions together in a single scope. It is used to define objects and specify the variables and the functions that can be accessed from outside the scope of the function.

What is the main advantage of using the module pattern in JavaScript?

The Javascript module pattern enables the implementation of the closure principle providing the control of privacy in your methods so that third party applications or modules cannot access data in variables or overwrite it.

What makes a JavaScript module?

A module in JavaScript is just a file containing related code. In JavaScript, we use the import and export keywords to share and receive functionalities respectively across different modules. The export keyword is used to make a variable, function, class or object accessible to other modules.

When would you use the revealing module pattern?

Revealing module pattern is a design pattern, which let you organise your javascript code in modules, and gives better code structure. It gives you power to create public/private variables/methods (using closure), and avoids polluting global scope (If you know how to avoid that).


1 Answers

I am just not sure of the purpose of deps array.

You seem to be confused on the purpose of the whole MyModules object, don't you?

The define method can be used to declare a module, with a name, an array of dependencies, and a factory function:

  • The name is the string under which the module object will be stored in that modules dictionary
  • The deps array contains the names of the modules on which the currently declared module depends on.
  • The impl function will be called to create the module object that will be available under the name. It does get passed the module objects to which the names in the deps array were resolved.

Why doesn't script try to put data on first call to it (from MyModules.define("bar",[],function()) ? Why does script make second call to define (MyModules.define("foo",["bar"], function(bar))?

It means to declare a module with the name bar without any dependencies, and to declare a module with the name foo that depends on bar. Typically, these two declarations would be placed in different scripts.

This code modules[name] = impl.apply(impl,deps) - Each callbacks, do not use 'this'.. so was apply necessary here?

Yes, apply is necessary here to pass arbitrary many arguments to the function. However, passing the impl function for the this value does indeed not make any sense, null would be more appropriate here.

A better and more understandable definition would be

function define(moduleName, dependencyNames, factory) {
    var dependencies = [];
    for (var i=0; i<dependencyNames.length; i++) {
        dependencies[i] = get(dependencyNames[i]); // resolve name
    }
    modules[moduleName] = factory.apply(null, dependencies);
}
like image 142
Bergi Avatar answered Nov 15 '22 23:11

Bergi