简体   繁体   中英

Getting the name of variable which holds an object, from the function resides in the object

Suppose an object is declared as follows

var object1 = {
    getName: function() {
        alert(name)
    }
};

Is there a way to alert "object1" from getName ?

If you declare an object like object literal then the answer is no, you can't get variable name. You can however declare it using constuctor:

function Obj() {
    this.getName = function() {
        console.log(this.constructor.name);
    }
}
new Obj().getName(); // "Obj"

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