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 ?
}
}
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 ?
}
}
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();
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.