Skip to content

Instantly share code, notes, and snippets.

@smaje99
Last active March 14, 2022 13:52
Show Gist options
  • Select an option

  • Save smaje99/8ce081287cd7f1bd11a38e38ccfa2b7c to your computer and use it in GitHub Desktop.

Select an option

Save smaje99/8ce081287cd7f1bd11a38e38ccfa2b7c to your computer and use it in GitHub Desktop.
Callable Object Literal
/**
* 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