功能:displayName
Non-standard: This feature is non-standard and is not on a standards track. Do not use it on production sites facing the Web: it will not work for every user. There may also be large incompatibilities between implementations and the behavior may change in the future.
Function 实例的可选 displayName 属性指定函数的显示名称。
¥The optional displayName property of a Function instance specifies the display name of the function.
值
描述
¥Description
与 name 属性相比,控制台和分析器可能更喜欢 displayName 属性(如果存在)显示为函数名称。
¥The displayName property, if present, may be preferred by consoles and profilers over the name property to be displayed as the name of a function.
在浏览器中,只有 Firefox 控制台使用了此属性。React devtools 在显示组件树时也会使用 displayName 属性。
¥Among browsers, only the Firefox console utilizes this property. React devtools also use the displayName property when displaying the component tree.
Firefox 做了一些基本尝试来解码可能由 匿名 JavaScript 函数命名约定 算法生成的 displayName。检测到以下模式:
¥Firefox does some basic attempts to decode the displayName that's possibly generated by the anonymous JavaScript functions naming convention algorithm. The following patterns are detected:
- 如果 displayName以字母数字字符、_和$序列结尾,则显示最长的此类后缀。
- 如果 displayName以[]括起来的字符序列结尾,则显示该序列时不带方括号。
- 如果 displayName以字母数字字符序列结尾,_后跟一些/、.或<,则返回的序列不带尾随/、.或<字符。
- 如果 displayName以字母数字字符序列结尾,并且_后跟(^),则显示的序列不带(^)。
如果以上模式均不匹配,则显示整个 displayName。
¥If none of the above patterns match, the entire displayName is displayed.
示例
设置显示名称
动态更改显示名称
¥Changing displayName dynamically
你可以动态更改函数的 displayName:
¥You can dynamically change the displayName of a function:
const object = {
  // anonymous
  someMethod: function someMethod(value) {
    someMethod.displayName = `someMethod (${value})`;
  },
};
console.log(object.someMethod.displayName); // undefined
object.someMethod("123");
console.log(object.someMethod.displayName); // "someMethod (123)"
清理显示名称
¥Cleaning of displayName
Firefox 开发工具会在显示 displayName 属性之前清理一些常见模式。
¥Firefox devtools would clean up a few common patterns in the displayName property before displaying it.
function foo() {}
function testName(name) {
  foo.displayName = name;
  console.log(foo);
}
testName("$foo$"); // function $foo$()
testName("foo bar"); // function bar()
testName("Foo.prototype.add"); // function add()
testName("foo ."); // function foo .()
testName("foo <"); // function foo <()
testName("foo?"); // function foo?()
testName("foo()"); // function foo()()
testName("[...]"); // function ...()
testName("foo<"); // function foo()
testName("foo..."); // function foo()
testName("foo(^)"); // function foo()
规范
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also