Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
156
rated 0 times [  163] [ 7]  / answers: 1 / hits: 19482  / 10 Years ago, thu, october 9, 2014, 12:00:00

In JavaScript, functions are simply objects that can be invoked. So what is the easiest way for the body of a function to reference the actual function object?



this can be used to reference the containing object that a function (or more specifically, a method) is called from. But I believe this never refers to the actual function object itself.



Obviously, bind, call, or apply could be used to change the value of this for the function. Or bind could be used to create a version of the function that is always given a reference to itself as its first parameter.



But is there any simpler way? I suspect not, but I could be wrong.


More From » javascript

 Answers
20

I cannot think of a case where a named function-expression cannot substitute for an anonymous function-expression. So I would suggest naming the function if you are going to call it from within itself (i.e., if you are going to use recursion):



function myFunc(someArg) {
...
...
myFunc(someNewArg);
}


This works even if it is a reference:



var myFunc = function(someArg) {
...
}


You can even use a recursive IIFE (immediately-invoked function expression) if you don't want to pollute the namespace:



(function myFunc(arg) {
...
myFunc(someOtherArg);
})(0); //some initial value


Furthermore, doing something like this:



someOtherFunction(function myFunc(arg) {
...
myFunc(otherArg);
});


Also works and won't pollute the namespace.


[#69181] Tuesday, October 7, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gregoriocoya

Total Points: 549
Total Questions: 111
Total Answers: 104

Location: Saint Helena
Member since Mon, Jan 16, 2023
1 Year ago
;