Skip to content

Instantly share code, notes, and snippets.

@ryanmorr
Last active March 29, 2024 00:30
Show Gist options
  • Save ryanmorr/4a2f5d0feaef96155aa2ff507b480bef to your computer and use it in GitHub Desktop.
Save ryanmorr/4a2f5d0feaef96155aa2ff507b480bef to your computer and use it in GitHub Desktop.
Detect if a function is a constructor
// https://stackoverflow.com/a/46759625
function isConstructable(fn) {
try {
Reflect.construct(function () {}, [], fn);
return true;
} catch (e) {
return false;
}
}
// Usage:
isConstructable(Array); //=> true
isConstructable(Function); //=> true
isConstructable(class {}); //=> true
isConstructable(class {}.bind()); //=> true
isConstructable(function() {}); //=> true
isConstructable(function() {}.bind()); //=> true
isConstructable(new Function()); //=> true
isConstructable(() => {}); //=> false
isConstructable((() => {}).bind()); //=> false
isConstructable(async () => {}); //=> false
isConstructable(async function() {}); //=> false
isConstructable(function * () {}); //=> false
isConstructable({ foo() {} }.foo); //=> false
isConstructable(Function.prototype); //=> false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment