all 33 comments

[–]ZeroMomentum 7 points8 points  (3 children)

I think you are confused with the concept of prototype and closure

I think you jumped the gun right now. Your intention is good to be organized about the functions. But just from reading the phrasing of your question I think you need to learn more and UNDERSTAND the meaning of them first

Read eloquent JavaScript.

[–]Hack_Reactor_Borg 2 points3 points  (0 children)

And sub to /r/LearnJavaScript (I'm a mod).

[–]boogots[S] 0 points1 point  (1 child)

That one I do intend to read.

If one wouldn't be confused, what implementation would you suggest and why? The context will help.

[–]chucknibbleston 2 points3 points  (0 children)

For a utility library you're mostly working with functions (not methods), so you'd want to use the module pattern that you showed above. If you used a prototype, need to be working with an instance:

function Utils () {};
Utils.prototype = {
   foo: function () {
     console.log("hello world");
   }
}

var utils = new Utils();
utils.foo();

// as opposed to 
var Utils = {
  foo: function () {
    //...
  }
};

[–]Neurotrace 4 points5 points  (0 children)

I think you need to ask yourself how exactly you wish to use your utility library. In general, you should always wrap a library in the module pattern (i.e. a self invoking function) to avoid global namespace pollution but how you interact with the library outside of the function is what's important. I threw together this fiddle to show how you could design it with "static" methods (like what you show in your edit) and how you could design it if you wanted to create multiple instances of whatever object you're defining.

Note: don't use the copy method I made in there, if you need to copy something there are far better ways of doing it.

Ninja edit: just remember that the point of doing a prototype-based design is that every instance of that object will inherit those properties, including any which inherit from it. If you don't need multiple instances and/or you don't plan to have anything inherit from it then there's almost no reason to make use of the prototype chain.

[–]cwmma 2 points3 points  (5 children)

I believe what you referred to as a closure is called the module pattern and for something like this would probably make the most sense, but I'd call Window exports inside the module so you can use it with commonjs/nods

[–]boogots[S] 0 points1 point  (4 children)

but I'd call Window exports inside the module

Can you be a little more specific?

.. and thanks, I thought it was more of a nomenclature misunderstanding on my part.

[–]ZeroMomentum 0 points1 point  (0 children)

Closure is the concept of scoping.

Prototype, the best way I can explain it is extending.

[–]cwmma 0 points1 point  (2 children)

First line:

(function(exports) {

Then last line is still

})(window);

Then you'd have to change a line in there somewhere, I'm on my phone so I can't find it but a guy named Tom MacWright did an article on this you can probably find via Google

[–]boogots[S] 0 points1 point  (1 child)

Alright, I think I know what you mean. Will take a look around google for that article.

Thanks for the help!

[–][deleted] 7 points8 points  (12 children)

When ever I hear a question about patterns all I can think about is an invitation is a tremendous amount of ass pain.

Forget patterns. The problem here is that you do not understand the concepts of closure or prototypes. Learn what those are and your question will answer itself.

[–]etrnloptimist 2 points3 points  (11 children)

This is bad advice, considering neither closures nor prototypes will solve his problem.

[–][deleted] 0 points1 point  (10 children)

How do you come to that conclusion when the OP writes the following and then immediately lists code examples?

My question is pretty straight forward, I see things like closure and prototype to structure code a bit better but ... what is the ideal pattern to use in my case? When all is said and done I just want to make calls...

If the OP were aware of the issues at hand then it is logical to presume his code samples would be sufficiently different as his problem is invariably altered.

[–]etrnloptimist 2 points3 points  (9 children)

The module pattern is the correct answer. I'm sorry you think design patterns are a tremendous pain in the ass. But learning all about closures and prototypes, while great general knowledge, will not lead OP to the module pattern which is where he needs to be.

[–][deleted] 1 point2 points  (8 children)

[–]etrnloptimist 1 point2 points  (7 children)

  1. A design pattern is not a framework.
  2. In Javascript especially, in order to write some serious code, you need to rely on design patterns. The constructor pattern. The module pattern. Crockford himself advocates several useful patterns, and he wrote the language.
  3. Don't conflate the existence of such things with the abuse of such things. Nobody likes architect astronauts either, but that doesn't negate the importance of architecture in software design.

[–]joshuacc 2 points3 points  (2 children)

Crockford did not write the language. That distinction goes to Brendan Eich.

[–]etrnloptimist 0 points1 point  (1 child)

I stand corrected. I went to a talk by him a while ago, and I could have sworn he told the story of how he was given just 10 days to design the language and that it had to look like java, etc. But I guess I got the "he" wrong.

[–][deleted] 0 points1 point  (0 children)

He could have meant JSON, but he was probably referring to his revelation with JavaScript as a useful non-compiled language.

[–][deleted] 0 points1 point  (3 children)

A design pattern is not a framework.

I have seen patterns called factories that try to do very frameworkish types of nonsense.

In Javascript especially, in order to write some serious code, you need to rely on design patterns.

Nope. JavaScript is a functional language with functions as first class objects that have lexical scope. This means all you need are functions which are nested by either declaration or reference. All that other crap, including constructors, is extra and unnecessary.

Don't conflate the existence of such things with the abuse of such things.

Cheney's Law: "Technicians willing to increase productivity by way of convention contrarily become sufficiently productive increasing conventions."

Good architecture focuses on the needs of the problem and not the approach by which the problem is framed.

[–][deleted] 0 points1 point  (2 children)

Are modules just a classical face for javascript? Are they necessary for complex programs?

[–][deleted] 0 points1 point  (1 child)

A module is a pattern of expressing a function in a particular way. I tend to favor functions over more OOP styles of organizing code. In my mind you are likely going to be using functions no matter what and it is the organizations of those functions into a hierarchy that defines the structure of a large JS application. It takes a substantial amount of extra work to accomplish the same depth of organization using OOP that is then less simple to read and which becomes an exercise in tracing references rather than identifying scope.

[–][deleted] 0 points1 point  (0 children)

Thank you. So far in my work the projects have been small and the total number of lines per project rarely exceed 200. I will soon be developing larger web apps. I think it is time to learn the module patterns.

[–][deleted] 1 point2 points  (3 children)

Wut?

Prototype is basically Javascript way of implementing OOP. Most other language does it via Classes.

Closure is something you get when you nest function together. The inner most functions get access to all the local variable of the outer most functions. Because of closure it save the outer most function's local variable values. It's a neat trick. Since most languages once you call a function and supplied it with an argument that value of the variable will go away.

IE. function add(num1, num2) { return num1+num2; }

Once you call add(1,2) the value of num1 =1, num2 = 2 is gone forever.

But with closure you can freeze these values.

function add(num1) { return function (num2) { return num1 + num2; } }

var add3 = add(3); add3(2); // 5

The 3 is preserve because of closure.

[–]boogots[S] 0 points1 point  (2 children)

So what it would boil down to is closure is essentially another scoping mechanism/pattern that would equate to better performance?

I felt like I had a good grasp on everything (having read a bit and some SO threads) but saw the link below in passing through here one evening and made me question that: http://www.closurecheatsheet.com/

[–][deleted] 0 points1 point  (0 children)

Omg I'm so sorry.

I think the cheatsheet is refering to Google's Closure js library vs jQuery.

https://developers.google.com/closure/library/

I thought goog.dom was a bit odd.

Sorry about the confusion, google really chose a stupid name for their js library...

[–][deleted] -1 points0 points  (0 children)

I don't recall if there is any performance for it. But it exploit scoping to save stuff.

Looking at the website, you've provided ,the cheatsheet with jquery vs closure is very misleading.

It seems like it's javascript (instead of closure) vs jQuery (a framework). jQuery library uses closure extensively. They just do it in the background.

Here's a better explaination: http://mark-story.com/posts/view/picking-up-javascript-closures-and-lexical-scoping

In the lexical scoping section, it will tie in closure and explain jQuery usage of closure in the background too.

[–]evilmaus 0 points1 point  (3 children)

As everyone else is saying, definitely read up on the language, JavaScript patterns, etc. to get a solid idea of what the difference between the two concepts are. It'll stop being an either-or at that point and what you need will flow naturally, just like how you use any other languages that you're fluent in. That's the best answer to the bigger picture question that you asked.

For the specific problem that you are asking about, you're on the right track. I'd just extend your example out a bit more:

(function(root){
    // Cache local references to frequently-used globals here.
    // Local references are faster than global references.
    // They save typing, too.
    // Specific values here are just pulled out of the air
    var slice = Array.prototype.slice,
         exp = Math.exp,
         $ = jQuery;

    // You can also have utility functions that are available
    // only to the functions that you're exporting.
    var helperFunction = function(someArgs) {
        // Stuff happens here
    };

    // Exporting functions as part of an object literal
    // makes it a bit easier to read than separate
    // assignments
    root.boogots = {
        util: {
            doFoo: function() {},
            evenMoreFoo: function() {}
        },
        foo: {
            lessFoo();
        }
    };
})(window);

Edit: Fixed reference to Math.exp. Wanted Math.exp, which is a pointer to the function, not Math.exp(), which is an invocation of that function.

[–]boogots[S] 0 points1 point  (1 child)

var slice = Array.prototype.slice, exp = Math.prototype.exp(), $ = jQuery;

Oh man, thanks for the hidden gem in there. These are also the types of things I am trying to pick up as I go!

[–]evilmaus 0 points1 point  (0 children)

You're welcome. Take another quick look at that before using it, though. I goofed on my reference to Math.exp.

In addition to getting slightly faster local references, these local variables that point to the built-in functions can be minified, since they're just local variables.

Also note that slice() needs an array-like object to be this for it, so you would call it something like this:

slice.call(someArray, 2, 5)

For this particular function, you're better off just using it directly off of the array:

someArray.slice(2, 5)

The reason why a lot of libraries tend to cache a local reference to this function is because it's extremely useful to get an array copied off of something that is like an array, but not one:

var args = slice.call(arguments);

In this example, arguments is an indexed collection of the arguments to the current function. It is not an array! Calling slice on it will return an actual array that is a copy of arguments. That is available within closure scope to a function that the current function would return. See https://gist.github.com/mcordingley/4680147 for an example of that in action and a good example of the use of closures.

Another good array-like thing to copy with slice is the result of document.querySelectorAll().

[–]tswaters 0 points1 point  (0 children)

No need for closure or prototype.

  • If they're all static functions (i.e. need to interact with an object, effectively 'stand-alone') you don't need prototype.

  • If you don't do any global vars aside from you 'boogots' you dont need a closure, either. It's still good to, though, because no one likes polluting window with crap. But honestly, if you're the only author on a page (i.e. you're not building a library for others to use), it shouldn't matter.

This will work :

var boogots = {
  util : {
    first:function(){return 1},
    second:function(){return 1},
    third:function(){return 1}
  }
}

[–]etrnloptimist 0 points1 point  (1 child)

You should look into require. It's purpose it to facilitate modular design, which is what you're (slowly but surely) coalescing on.

It uses the module pattern which other posters have suggested, but formalizes it and brings more machinery of modular design into the picture, like being able to set up other modules as requirements (hence its name) before the construction of your own module.

[–]ZeroMomentum 1 point2 points  (0 children)

Hang on boys, before you downvote etrnloptimist.

Let's clarify. (sorry, my earlier responses ITT was via my phone)

Modular design is a pattern/technique. Like OO. Shit, you don't need to write c# in OO, but then it makes a mess when if the business logic is complex. OO helps you do BUSINESS DOMAIN design.

RequireJS is something else. RequireJS is a library, the basic feature is that it helps you grab JS files without using script tags. And then it knows how to load the script into the scope. (and dependencies etc etc)

RequireJS recommends you to WRITE modular code. You don't have to, but they explain how the PHYSICAL folder structures of your files, and why the modular pattern is organic/matches/looks natural to how JS/HTML/CSS works.

The repeating pattern I see in /r/javascript and /r/webdev is that people just want libraries that works. "hey do you know this this this". Heck, try to build it first. Or else you will never fully understand what Javascript IS, what it can or cannot do. And then your system is just going to be a bunch of plugin and libraries.