Getting the object variable name in JavaScript

前端 未结 3 698
野性不改
野性不改 2020-12-02 00:51

I am creating a JavaScript code and I had a situation where I want to read the object name (string) in the object method. The sample code of what I am trying to achieve is s

相关标签:
3条回答
  • 2020-12-02 01:02

    Depending on what your needs are, there are some creative solutions. The main place I want to know a variable name is when I'm debugging.

    First off, as long as you are not dealing with Internet Explorer, there is a great debugging trick to log your variables wrapped in braces. The console will show you the details of your "object"... which has only one key, the exact name of your variable!

    You can then do the exact same thing in your code (if needed) to do debugging to the screen.

        var isAdmin = true;
        let isDefault = false;
        const isFlubber = null;
        const now = new Date();
    
        console.log({isAdmin});
        console.log({isDefault});
        console.log({isFlubber});
        console.log({now});
        
        //You can also use console.dir() or console.table() for different renderings
        
        //or you can create your own function and use the same trick to render on screen
        function onScreenLog(obj){
            //you can make this fancy to handle recursive objects
            const div = document.getElementById('onscreen-log');
            for(const [key, value] of Object.entries(obj)){
              div.innerHTML += key + ': <b>' + value + '</b><br/>'; 
            }
        }
        onScreenLog({isAdmin});
        onScreenLog({isDefault});
        onScreenLog({isFlubber});
        onScreenLog({now});
        
    <div id="onscreen-log" style="background=color:#fffedf;border:1px solid #ffffd;font-family:sans-serif;height:75px;padding:2px;"></div>

    0 讨论(0)
  • 2020-12-02 01:04

    This is definitely possible but is a bit ugly for obvious reasons. I think this can have some application in debugging. The solution makes use of the ability to get the line number for a code using Error object and then reading the source file to get the identifier.

    let fs = require('fs');
    class Foo {
        constructor(bar, lineAndFile) {
            this.bar = bar;
            this.lineAndFile = lineAndFile;
        }
        toString() {
            return `${this.bar} ${this.lineAndFile}`
        }
    }
    let foo = new Foo(5, getLineAndFile());
    
    console.log(foo.toString()); // 5 /Users/XXX/XXX/temp.js:11:22
    readIdentifierFromFile(foo.lineAndFile); // let foo
    
    function getErrorObject(){
        try { throw Error('') } catch(err) { return err; }
    }
    
    function getLineAndFile() {
        let err = getErrorObject();
        let callerLine = err.stack.split("\n")[4];
        let index = callerLine.indexOf("(");
        return callerLine.slice(index+1, callerLine.length-1);
    }
    
    function readIdentifierFromFile(lineAndFile) {
        let file = lineAndFile.split(':')[0];
        let line = lineAndFile.split(':')[1];
        fs.readFile(file, 'utf-8', (err, data) => { 
            if (err) throw err; 
            console.log(data.split('\n')[parseInt(line)-1].split('=')[0].trim());
        }) 
    }
    
    0 讨论(0)
  • 2020-12-02 01:10

    This is not possible in JavaScript. A variable is just a reference to an object, and the same object can be referenced by multiple variables. There is no way to tell which variable was used to gain access to your object. However, if you pass a name to your constructor function you could return that instead:

    // Define my object
    function TestObject (name) {
        return {
            getObjectName: function() {
                return name
            }
        };
    }
    
    // create instance
    var a1 = TestObject('a1')
    var a2 = TestObject('a2')
    
    console.log(a1.getObjectName()) //=> 'a1'
    
    console.log(a2.getObjectName()) //=> 'a2'

    0 讨论(0)
提交回复
热议问题