How useful is the Function.name property?

var func1 = function() {} console.log(func1.name); // func1 

Is there a real-time use of this property from a javascript developer perspective?

+5
source share
2 answers

You can use it for debugging purposes when passing a function as a parameter to another function, for example:

 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); } 
+3
source

The answer to this question will be quite wide, as there are hundreds of examples of using the name property. They are described in detail in the JavaScript documentation . A few of the following examples.

Change the name of a function.

 var newName = "xyzName"; var f = function () {}; Object.defineProperty(f, 'name', {value: newName}); console.log(f.name); // will output xyzName 

To register the class stack, we can get the name of the constructor, as in the following example.

 function a() {}; var b = new a(); console.log(b.constructor.name); // will output a 

Get the name of the function if it is not anonymous.

 var getRectArea = function area(width, height) { return width * height; } getRectArea.name; //will output area 
+1
source

Source: https://habr.com/ru/post/1275986/


All Articles