implementation.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. var IsCallable = require('es-abstract/2021/IsCallable');
  3. var functionsHaveNames = require('functions-have-names')();
  4. var callBound = require('call-bind/callBound');
  5. var $functionToString = callBound('Function.prototype.toString');
  6. var $stringMatch = callBound('String.prototype.match');
  7. var classRegex = /^class /;
  8. var isClass = function isClassConstructor(fn) {
  9. if (IsCallable(fn)) {
  10. return false;
  11. }
  12. if (typeof fn !== 'function') {
  13. return false;
  14. }
  15. try {
  16. var match = $stringMatch($functionToString(fn), classRegex);
  17. return !!match;
  18. } catch (e) {}
  19. return false;
  20. };
  21. var regex = /\s*function\s+([^(\s]*)\s*/;
  22. var functionProto = Function.prototype;
  23. module.exports = function getName() {
  24. if (!isClass(this) && !IsCallable(this)) {
  25. throw new TypeError('Function.prototype.name sham getter called on non-function');
  26. }
  27. if (functionsHaveNames) {
  28. return this.name;
  29. }
  30. if (this === functionProto) {
  31. return '';
  32. }
  33. var str = $functionToString(this);
  34. var match = $stringMatch(str, regex);
  35. var name = match && match[1];
  36. return name;
  37. };