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'
Junho Kim
  • 257
  • 1
  • 3
  • 10
  • You cannot necessarily assume access to [`arguments.callee`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/callee) so you can't do this, but if you can assume it, do a `for..in` over `this` testing for `arguments.callee` – Paul S. Jan 27 '16 at 13:19

1 Answers1

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
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • @JunhoKim [**ES6 is the same as ES5 on this**](http://www.ecma-international.org/ecma-262/6.0/#sec-arguments-exotic-objects); 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. – Paul S. Jan 29 '16 at 15:46