Skip to content

Instantly share code, notes, and snippets.

@vseventer
Last active July 10, 2016 10:31
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vseventer/5324295 to your computer and use it in GitHub Desktop.
Save vseventer/5324295 to your computer and use it in GitHub Desktop.
Create a callable object in JavaScript which returns an isolated clone of itself. This is *not* a class, hence using the new keyword has no effect.
// How to define:
// --------------
var callableObjectFn = function() {
// Use CallableObject as name in constructor function, but also when setting property below.
var CallableObject = (function(CallableObject) {
return function() {
return CallableObject();
};
}(callableObjectFn));
CallableObject.property = 'value';
return CallableObject;
};
var CallableObject = callableObjectFn();
// How to use:
// -----------
var foo = CallableObject;
foo.property = 'anotherValue';
foo.anotherProperty = 1;
var bar = CallableObject();
bar.property = 'yetAnotherValue';
bar.anotherProperty = 2;
var baz = bar();
baz.property = 'yetAgainAnotherValue';
baz.anotherProperty = 3;
var qux = CallableObject();
// Output: function() { return CallableObject(); }.
console.log(CallableObject);
// Output: anotherValue, yetAnotherValue, yetAgainAnotherValue, value.
console.log(foo.property, bar.property, baz.property, qux.property);
// Output: 1, 2, 3, undefined.
console.log(foo.anotherProperty, bar.anotherProperty, baz.anotherProperty, qux.anotherProperty);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment