implementation.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. var IsCallable = require('es-abstract/2023/IsCallable');
  3. var HasOwnProperty = require('es-abstract/2023/HasOwnProperty');
  4. var functionsHaveNames = require('functions-have-names')();
  5. var callBound = require('call-bind/callBound');
  6. var $functionToString = callBound('Function.prototype.toString');
  7. var $stringMatch = callBound('String.prototype.match');
  8. var toStr = callBound('Object.prototype.toString');
  9. var classRegex = /^class /;
  10. var isClass = function isClassConstructor(fn) {
  11. if (IsCallable(fn)) {
  12. return false;
  13. }
  14. if (typeof fn !== 'function') {
  15. return false;
  16. }
  17. try {
  18. var match = $stringMatch($functionToString(fn), classRegex);
  19. return !!match;
  20. } catch (e) {}
  21. return false;
  22. };
  23. var regex = /\s*function\s+([^(\s]*)\s*/;
  24. var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing
  25. var objectClass = '[object Object]';
  26. var ddaClass = '[object HTMLAllCollection]';
  27. var functionProto = Function.prototype;
  28. var isDDA = function isDocumentDotAll() {
  29. return false;
  30. };
  31. if (typeof document === 'object') {
  32. // Firefox 3 canonicalizes DDA to undefined when it's not accessed directly
  33. var all = document.all;
  34. if (toStr(all) === toStr(document.all)) {
  35. isDDA = function isDocumentDotAll(value) {
  36. /* globals document: false */
  37. // in IE 6-8, typeof document.all is "object" and it's truthy
  38. if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) {
  39. try {
  40. var str = toStr(value);
  41. // IE 6-8 uses `objectClass`
  42. return (str === ddaClass || str === objectClass) && value('') == null; // eslint-disable-line eqeqeq
  43. } catch (e) { /**/ }
  44. }
  45. return false;
  46. };
  47. }
  48. }
  49. module.exports = function getName() {
  50. if (isDDA(this) || (!isClass(this) && !IsCallable(this))) {
  51. throw new TypeError('Function.prototype.name sham getter called on non-function');
  52. }
  53. if (functionsHaveNames && HasOwnProperty(this, 'name')) {
  54. return this.name;
  55. }
  56. if (this === functionProto) {
  57. return '';
  58. }
  59. var str = $functionToString(this);
  60. var match = $stringMatch(str, regex);
  61. var name = match && match[1];
  62. return name;
  63. };