IT Man
IT Man

Reputation: 1036

How to get function self reference from within that function?

is there any way to get function reference when i'm inside function?

var arrayOfFunction = [ myFunction ];

arrayOfFunction[0]();

function myFunction() {
    removeFromArray( thisFunctionReference ) // how to get function self reference here?
};

function removeFromArray(functionRef) {
    index = arrayOfFunction.indexOf(functionRef);
    if (index > -1) {
        arrayOfFunction.splice(index, 1);
    }
}

Upvotes: 3

Views: 421

Answers (2)

Willem van der Veen
Willem van der Veen

Reputation: 36620

In JavaScript, functions are first class members and thus behave like any other object. You can just refer to it by name like this:

myFunction.property = 5;

function myFunction() {
  console.log(myFunction.property) //logs 5
  console.log(myFunction) // logs the function 
};

myFunction();

Upvotes: 3

Wand Maker
Wand Maker

Reputation: 18762

You can do following as well

removeFromArray(arguments.callee);

Whether you should do that or not will depend on whether you are planning to use "strict" mode in your app. More info in documentation.

Upvotes: -1

Related Questions