Get variable name in JavaScript

5

I have the following:

function Class(){
  this.getInstanceName = function(){
    // ¿Es posible obtener el nombre de la instancia? algo como:
    return getInstanceName();
  };
}

var classInstance = new Class();

// debe imprimir: classInstance
console.log(classInstance.getInstanceName());

Is it possible to get the instance name classInstance in JavaScript?

    
asked by learnercys 29.12.2015 в 18:52
source

3 answers

4

Some time ago I made this class that exports 2 methods: One that returns the name of the function (the name in the declaration)

getFunctionName(function myFunction(a, b, c){}) that returns "myFunction" or an empty string if it is an anonymous function.

and this one that returns the name of the parameters:

getParameterNames(function myFunction(a, b, c){}) that returns "[a, b, c]"

Keep in mind that if you use it like this:

var fn = function myFunction(a, b, c) {};
getFunctionName(fn); 

It also returns myFunction , since it takes into account the declaration of the function, not the alias with which it is passed. Therefore it will not work as you ask, but it is what can be done in javascript.

These methods basically parse the function to obtain the data (use function.toString to do it). Includes some ECMAScript 2015 support.

var reflection = (function () {
    'use strict';

    var stripComments = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg,
        argumentNames = /([^\s,]+)/g,
        reflection = {};

    /**
     * Checks if 'expr' is a function 
     * @param {} expr 
     * @returns {} 
     */
    function isFunction(expr) {
        return typeof expr === 'function';
    }

    /**
     * Gets the function parameter names as an Array.
     * 
     * usage example: getParameterNames(function (a,b,c){}); // ['a','b','c']
     * @param {} func the function. 
     * @returns {} An ordered array of string with the parameters names, or an empty array if the function has no parameters.
     */
    function getParameterNames(func) {
        var fnStr = func.toString().replace(stripComments, '');
        var result = fnStr.slice(fnStr.indexOf('(') + 1, fnStr.indexOf(')')).match(argumentNames);
        if (result === null)
            result = [];
        return result;
    }

    /**
     * Gets the function name.
     * 
     * @param {} func the function. 
     * @returns {} the name of the function, empty string if is an anonymous function. 
     */
    function getFunctionName(func) {
        if (!isFunction(func)) throw new TypeError('"func" must be a function.');
        // ECMAScript 2015
        if (func.name) {
            return func.name;
        }
        // old fashion way
        var fnStr = func.toString().substr('function '.length),
            result = fnStr.substr(0, fnStr.indexOf('('));
        return result;
    }

    // Module Exports
    reflection.isFunction = isFunction;
    reflection.getFunctionName = getFunctionName;
    reflection.getParameterNames = getParameterNames;
    return reflection;
}());
    
answered by 29.12.2015 / 19:01
source
3

You can extract the name of the function from a stack trace of an object Error :

<script type="text/javascript">
function foo() {
    var e = new Error();
    var me = e.stack.match(/at ([a-z0-9_.]+) \(/i);
    console.log("me = " + me[1]);
}
foo();   
</script>

You may want to put that functionality in a common function, and then you should look for the second function in the stack trace:

<script type="text/javascript">
function calledFrom() {
    var e = new Error(); 
    stack = e.stack.split("\n");
    caller = stack[2].match(/at ([a-z0-9_.]+) \(/i);
    return caller[1];   
}
function foo() {
    console.log("Mi nombre es " + calledFrom());
}
foo();
var obj = {};
obj.bar = foo;
obj.bar();
</script>

The answer in the console:

  

My name is foo
  My name is Object.foo

    
answered by 29.12.2015 в 22:03
2

Apparently at the moment there is no way to get the name of the variable in JavaScript, I found several sources that match it and I quote them below. Instead I found an alternative taken from a PHP code that translated into JavaScript; it works only for global variables in browsers (by object window ).

Solution (alternative)

function getNameVar(v) {
    for (var key in window) {
        if (window[key] === v)
        return key;
    }
    return false;
}

How to use:

var a = '123',
    b = 'abc';

getNameVar(a); // "a"

Original idea at: How to get a variable name as a string in PHP? - Stack Overflow

Translation: Javascript get name of instance of class - Stack Overflow

Variables in JavaScript are of primitive value or reference to an object. Where the value is a reference, then the thing referenced has no idea of the "name" of the variable that contains it.

Consider:

var foo = new Cosa();
var bar = foo;

So now foo.getInstanceName() what should return? or even:

(new Cosa()).getInstanceName();

If you want the instances to have a name, then give them a property and set the value you want it to have.

Other sources of support:

answered by 29.12.2015 в 19:13