Out of curiosity, what is the things you need to do to make that possible?
function myFunction() {
var a, b, func;
func = function () {
return {
attrA: function (attr) {
a = attr;
return this;
},
attrB: function (attr) {
b = attr;
return this;
},
toString: function () {
console.log([a, b].join(' '));
return this;
}
}
}
return func();
}
This allows us to call myFunction multiple times, set attributes (imagine it were createPerson instead, with a name, age, etc...) and not run into problems with state being shared.I like this question because it covers closures, this, objects and functions. It also doesn't qualify as a brain teaser, IMO.
That's debatable. It requires a piece of unusual thinking ('return this'), and a bit of magic (knowing about the 'this' magic variable), but once you've seen it, the answer's obvious, and it's pretty easy to replicate everywhere.
Example:
var a = function(x){ this.x = x+1; return this; }
var b = function(){ this.x *= 2; return this.x; }
a(3).b(); //result = 8