1

How can I get the key name "email" inside the function ? Is there a special context variable to do this ?

Thanks for help.

var user = {
  "email": function() {
    // How can I get the name of the key (email) inside the function ?
  }
}

2
  • There is no way to really know the name/key of the function without hard coding it. Commented Dec 8, 2017 at 19:45
  • 1
    Yeah, unfortunately anonymous functions are just that, anonymous. Commented Dec 8, 2017 at 19:50

2 Answers 2

1

A relatively new feature of JS will assign a name to an anonymous function expression based on the variable or property to which it is initially assigned.

You can access a function's name via arguments.callee.name

var bar = {
  baz: function() {
    console.log(arguments.callee.name);
  }
}

bar.baz();

Of course, if you copy the function elsewhere, it won't get a new name. The name is given to it at the time it is created.

var bar = {
  baz: function() {
    console.log(arguments.callee.name);
  }
}

bar.foo = bar.baz;

bar.foo();

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for tips but for arguments.callee.name, it is deprecated.
0

I will answer this by asking a question. Consider this scenario:

let myFunc = function(){ /* somehow returns the name */ };

let a = {
    funcA: myFunc
};

let b = {
    funcB: myFunc
};

Now, consider this:

a.funcA();
b.funcB();

What should they return? myFunc, funcA, or funcB? The answer is "it doesn't make sense".

This is why what you are trying to do is impossible. The function can be "owned" by different objects.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.