Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How to get the parent key inside a function?

I've some functions, stored in a collection/array and would like to get the key (function-name) without retyping it. Is there any short way to access it?

var functions_collection = {
    "function_x": function() {
        var name = "function_x";
        // name = this.key; <- how to get the key/function-name "function_x"?

        // some more code like:
        $(".function_x .button").val();

        alert(name);
    }
}

Edit: I'd like to avoid retyping the "function_x" inside the function itself and prefer to call it like this.key.

Sorry for the weird topic and thanks in advance!

Solution: A lot of good answers, but I was just looking for this snipped:

Object.keys(this)
like image 572
Mr. B. Avatar asked Jun 04 '13 18:06

Mr. B.


2 Answers

I'm not sure it's what you want but you can do this :

    var functions_collection = {};
    (function(name){
       functions_collection[name] = function(){
           // use name, which is the function
           alert(name);
       };
    })("function_x");

I'm not really sure it's better. But depending on your (unspecified) goal, there's probably a better solution.

like image 115
Denys Séguret Avatar answered Nov 15 '22 15:11

Denys Séguret


To get the name of the objects keys, you can use Object.getOwnPropertyNames(this) or in newer browsers just Object.keys(this), and that will get you an array of all and any keys the this object has :

var functions_collection = {
    function_x: function() {
        var name = Object.keys(this);
        console.log(name);
    }
}

FIDDLE

like image 42
adeneo Avatar answered Nov 15 '22 16:11

adeneo