var func1 = function() {}
console.log(func1.name); // func1
Is there any real-time usage of this property from the javascript developer's perspective?
Closures are important because they control what is and isn't in scope in a particular function, along with which variables are shared between sibling functions in the same containing scope.
Pros. Closure allows us private variables that are available even after a function task is finished. Closure enables us to store data in a separate scope and share it only where necessary.
The function's name property can be used to identify the function in debugging tools or error messages. It has no semantic significance to the language itself. To change it, use Object.
No, closures do not cause a function to be impure, as long as the closed value is constant (neither changed by the closure nor other code), which is the usual case in functional programming.
You can use it for debugging purposes when you pass function as a parameter to another function, for instance:
var fun1 = function(){};
function fun2(){};
var g = function(f){
console.log("Invoking " + f.name);
f();
}
if(Math.random() > 0.5){
g(fun1);
} else {
g(fun2);
}
The answer to this question will be quite broad, since there are hundreds of examples for the usage of property called name
. They are covered in detail in JavaScript documentation. Few of the examples are following.
Changing the function name.
var newName = "xyzName";
var f = function () {};
Object.defineProperty(f, 'name', {value: newName});
console.log(f.name); // will output xyzName
For logging the class stack we can get the constructor name as in the following example.
function a() {};
var b = new a();
console.log(b.constructor.name); // will output a
Get the function name if it's not anonymous.
var getRectArea = function area(width, height) {
return width * height;
}
getRectArea.name; //will output area
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With