Last active
March 29, 2024 00:30
-
-
Save ryanmorr/4a2f5d0feaef96155aa2ff507b480bef to your computer and use it in GitHub Desktop.
Detect if a function is a constructor
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
// 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