Jump to navigation

Code patterns

Module pattern

var modulePattern = modulePattern || {};

modulePattern.sayIt = function() {

  var public = {};
  public.settings = [true, false, true];
  var self = this;

  function init() {

    console.log('private');
    
  }
  
  public.speak = function(string) {
    
      console.log(string);
    
  }

  return public;
  

}

console.log(modulePattern.sayIt().settings);
modulePattern.sayIt().speak('something');
// Won't work as not public
//modulePattern.sayIt().init();

Codepen

Class Pattern

class Button {
  constructor(el) {
    this.el = el;
    this.el.addEventListener('click', evt => this.start());
  }
  start() {
    console.log('started');
  }
}

// External file
export default Button;
import Button from './Button';

const a = new Button(document.getElementById('a'));