// 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();
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.