Last active
March 14, 2022 13:52
-
-
Save smaje99/8ce081287cd7f1bd11a38e38ccfa2b7c to your computer and use it in GitHub Desktop.
Callable Object Literal
This file contains hidden or 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
| /** | |
| * It creates a function that has the same properties as the class it is called on. | |
| * @see {@link 'https://docs.python.org/3/reference/datamodel.html#object.__call__'} | |
| * @param cls - The object to be called. | |
| * @returns A function that is callable. | |
| */ | |
| function ObjectCallable(cls) { | |
| let func = () => func.__call__(this, arguments); | |
| for (let key in cls) func[key] = cls[key]; | |
| return func; | |
| } | |
| // Implementation | |
| obj = ObjectCallable({ | |
| attr1: 1, | |
| attr2: 'Hello world', | |
| __call__: () => 'I\'m Callable Object' | |
| }) | |
| obj() // I'm Callable Object |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment