ES6 modules

by black strings

HTML

ES6 modules

JavaScript

// this is the better way as you can hide private functions
// and expose public functions
// basically calling the function returns an object with mapping to private functions you want to expose
var Stats = function(id){
  
  // private - method 1
  var calc = (val) => {
  	return val * 2;
  }
  // private - method 2
  function add(val) {
  	return val + 1;
  }
  
  // nested calling of methods
  function test(x) {
  	return calc(x) + add(x);
  }
  
  // expose public variables and api
  return {
    calc: calc,
    add: add,
    test: test,
    id: id
  }
}
// end of method 1

const stats = new Stats(99);
const sum = stats.test(2);
console.log(sum);


// this is another way but is messier as it is not AS encapsulated
var Mod = {};
var Timer = function(){
	this.name = 'x';
};
Timer.prototype.calc = function(a,b){
	return a+b;
}
Mod.Timer = Timer;
// ---- end of method 2
var t = new Timer();
console.log(t.calc(2,2));


// method 3 - using classes
class Ball {
	roll() {
  	console.log('rolling');
  }
}
const b = new Ball();
b.roll();