Skip to content

Instantly share code, notes, and snippets.

@knowler
Last active January 17, 2025 08:14
Show Gist options
  • Save knowler/35618df14bca51b99990c60438d84588 to your computer and use it in GitHub Desktop.
Save knowler/35618df14bca51b99990c60438d84588 to your computer and use it in GitHub Desktop.
These can only be subclassed, not constructed on their own or called as a function.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target
class Special {
constructor() {
if (new.target === Special)
throw new TypeError("Failed to construct 'Special': Illegal constructor");
}
}
function AlsoSpecial() {
if (new.target === AlsoSpecial)
throw new TypeError("Failed to construct 'AlsoSpecial': Illegal constructor");
else if (new.target === undefined)
throw new TypeError("Failed to construct 'AlsoSpecial': Please use the 'new' operator, this special object constructor cannot be called as a function.");
}
class NotSoSpecial extends Special {}
function AlsoNotSoSpecial() {
// If you drop the sub-class argument, this will fail.
return Reflect.construct(AlsoSpecial, arguments, AlsoNotSoSpecial);
}
AlsoNotSoSpecial.prototype = Object.create(AlsoSpecial.prototype);
// All of these will fail
try { new Special() } catch(error) { console.error(error); }
try { Special() } catch(error) { console.error(error); } // Built-in error
try { new AlsoSpecial() } catch(error) { console.error(error); }
try { AlsoSpecial() } catch(error) { console.error(error); }
new NotSoSpecial(); // Works
new AlsoNotSoSpecial(); // Also, works
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment