简体   繁体   中英

get key name inside of it`s value function

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM