Last active
July 10, 2016 10:31
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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