JavaScript – best coding pattern

this or that ? bind or not-bind(this), prototype of prototype ? ehm..all the interesting   things, however better without them in your  code in JavaScript. There is perfect style finally – found in d3, check here: http://bost.ocks.org/mike/chart/ and used in dc.js as well , well described in the d3-cookbok book by Nick Qui Zhu sample code here similar post appeard here “javascript without this”

..it is worth to study the pattern, it will make your code beautiful, modern and readable. You will not need CoffeScript nor TypeScript nor whateverScript.  You even don’t need many other infrastructure or abstractions to get modules or classes  out of JavaScript. It is very elegant.

It is very simple:

function SimpleWidget(spec) {
  var instance = {}; //-- actual instance variable
  var description; // -- private variable

 //-- public API method
instance.foo = function () {
   return instance; //-- returns instance for chaining
 };

 //-- public API method
 instance.boo = function (d) {
   //-- getter of private variable
   if (!arguments.length) return description;

    description = d;  //-- setter of private var
    return instance; //-- returns instance for chaining
 }

 return instance; //-- returns instance for chaining
 }
 // usage
var widget = SimpleWidget({color: "#6495ed"})
            .boo("argument")
            .foo();

 

 

 

*** update 1

just came across this great presentation from JSConf.eu : http://2014.jsconf.eu/speakers/sebastian-markbage-minimal-api-surface-area-learning-patterns-instead-of-frameworks.html and this is exactly the way to think about all of the ‘abstracted stuff’ and syntax sugar or salt that is available today for JavaScript.

“It’s much easier to recover from no abstraction than the wrong abstraction.”

*** update 2

NPM and Browserify  is worth to look at, the way how the complex code is done for example in  MapBox-GL-JS . While I don’t like convoluted modules of modules and source maps with concatenated sources, the syntax and modularization is working well.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.