1

How do I get key names from it`s value nameless function?

What would be /*some code */ that get 'foo'

var obj = {
    foo: function () {
             console.log('Error found in ' + /* some code */);
         }
};

obj.foo(); // get 'Error found in foo'
1
  • You cannot necessarily assume access to arguments.callee so you can't do this, but if you can assume it, do a for..in over this testing for arguments.callee Commented Jan 27, 2016 at 13:19

1 Answer 1

1

By iterating over the properties of this using for..in you can test against arguments.callee

var o = {
    foo: function () {
        var k, found, pname = 'unknown';
        for (k in this) if (this[k] === arguments.callee) {
            found = true;
            break;
        }
        if (found) pname = k;
        console.log('Error found in ' + pname);
    },
    bar: "something else"
};

o.foo(); // Error found in foo

Please note that arguments.callee is forbidden in strict mode by ES5 spec.

In this case you would need a named function expression,

var o = {
    foo: function fizzbuzz() {
        var k, found, pname = 'unknown';
        for (k in this) if (this[k] === fizzbuzz) {
            found = true;
            break;
        }
        if (found) pname = k;
        console.log('Error found in ' + pname);
    },
    bar: "something else"
};

o.foo(); // Error found in foo

Finally,

  • If you are doing things where you can't guarantee enumerability for..in will not necessarily work, take a look here
  • If you've changed your this, there is no way for the function to know what you want without passing it a reference to your object in another way
Sign up to request clarification or add additional context in comments.

1 Comment

@JunhoKim ES6 is the same as ES5 on this; forbidden in strict mode. Arrow functions don't give you an arguments so you can't use it for them either. Best use a named function expression.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.