Question

I've got some functions like this:

function killOrphans(str) {
    return str.replace(/\s([\dwuioaz]{1})\s/gi, ' $1\u00a0');
}

which is generally a helper function to remove single letter words (orphans) from the end of a line (Polish typography demands to do this).

Question: how do you treat a library of such functions? A module in the global scope? extending jQuery? Extending the prototypes of String, Array etc.? (I don't think it's a good idea...). I think I'll go in the direction of underscore and create a module, but I'd be glad to hear real life examples of your way to do it.

Adam

Was it helpful?

Solution

In my project, I've used a variety of strategies for helper functions.

Extra methods on a view or a model.

var MyView = Backbone.View.extend({
  initialize: function(){...},
  render: function(){...},
  helper: function(){...}
});

Use a helper module.

var myHelpers = {
  foo: function(){...},
  bar: function(){...},
  baz: function(){...}
};

Extend an existing lib.

jQuery.fn.foo = function(){...};

Use an IIFE (best for functions you'd like to keep private)

var MyView = Backbone.View.extend({
  initialize: function(){...},
  render: function(){...},
  myMethod: (function(){
    function helper(){...}
    return function(){
      // do stuff here, using helper()
    }
  })()
});

Also, if you're not working in node.js which automatically provides a module system, it's worth using some strategy, such as browserify or requirejs, to export and import modules in a sane way, rather than having everything hang off the global namespace.

OTHER TIPS

It is a question for Nobelprize - how to structure Javascript code with such a dynamic language. There are a lot of patterns and library solutions for this problem. For example:

  • You can extend prototype but then you are creating coupling. You can create a module, but do you need module for one function ? You can use Requirejs, annonymous functions...

Best real life examples are in production code. Take a look how jQuery deals with structure. And also Backbone. Try to learn classic design patterns - they are source of gold for any JS developer.

My advice is to dig deeper into JS and discover why language is designed in such a way. My first language was Javascript but I didn't make any progress until I started to learn something more traditional like in OO sense.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top