What is the difference between following code bits:
function Foo(context) {
let mode;
function setMode(m) {
mode = m;
}
function doStuff() {
if(mode === 'param') {
// ... do stuff with context
} else {
// ... do different stuff with context
}
}
this.setMode = setMode;
this.doStuff = doStuff;
}
vs
function Bar(context) {
let mode;
function setMode(m) {
mode = m;
}
function doStuff() {
if(mode === 'param') {
// ... do stuff with context
} else {
// ... do different stuff with context
}
}
return {
setMode,
doStuff,
}
}
In Foo I use this to 'augment' the new instance of Foo function:
const f = new Foo();
f.setMode('param');
f.doStuff(stuff);
In Bar I return 'new' object with methods each time function Bar is called:
const b = Bar();
b.setMode('parampam');
f.doStuff(stuff);
Are there any benefits (performance? memory usage?) of using one way or another? return vs this?
I am familiar with lexical 'this' scope, and how closure works but I'd like to know if above choice is purely syntactical or it has performance implications?