Why function.name?
The Function.name () object returns the name of the specified function statement. Returns “anonymous” if the function does not have a name. More clearly:
- The function holds a variable function with the same name in the body.
- The name property holds the function name, so a named function is created.
let’s try to understand the logic with a small example:
let getFunction = function (variable) {
return variable;
}
let arr = getFunction.name;
console.log(arr)
getFunction
Since this is not anonymous function, it returned the function name to us.
The anonymous function is:
let getFunction = function (variable) {
return typeof variable;
}
getFunction.name
” “
Variables can remove the name of an anonymous function from the syntactic position.
let func = function () { }
let obj = {
arr: function(){}
}
console.log(func.name);
console.log(obj.arr.name);
func
arr
Short Method Naming
let f = {
arr() { }
};
console.log(f.arr.name);
arr
Bound Function Names
function func() {
};
let arr = func.bind({ name }).name;
console.log(arr)
bound func
Function names in classes
let func = {
get function1() { },
set function1(x) { }
};
let arr = Object.getOwnPropertyDescriptor(func, "function1");
console.log(arr.get.name);
console.log(arr.set.name);
get function1
set function1
JavaScript compressors and minifiers
Source code such as:
function Foo() {};
let foo = new Foo();
if (foo.constructor.name === 'Foo') {
console.log("'foo' is an instance of 'Foo'");
} else {
console.log('Oops!');
}
may be compressed to:
function a() {};
let b = new a();
if (b.constructor.name === 'Foo') {
console.log("'foo' is an instance of 'Foo'");
} else {
console.log('Oops!');
}
Source of this page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name
Browser Support
Chrome | 15 |
Edge | 15 |
Firefox | 1 |
Internet Explorer | no |
Opera | yes |
Safari | yes |
Android webview | yes |
Chrome for Android | yes |
Edge mobile | yes |
Firefox for Android | 4 |
Opera Android | yes |