简体   繁体   English

从函数获取持有对象的变量的名称驻留在对象中

[英]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 ? 有没有一种方法可以从getName警报"object1"

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: 但是,您可以使用constuctor进行声明:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从对象内部获取保存对象实例的变量名:Javascript - How to obtain the variable name which holds an object instance from within the object : Javascript 如果Javascript对象具有保存对函数的引用的属性,是否可以从函数本身中获取该属性名称? - If a Javascript object has a property which holds a reference to a function, can I get that property name from within the function itself? 哪个对象“持有” addEventListener? - Which object “holds” addEventListener? 如何使用持有数组名称的变量将对象文字添加到数组 - how to add an object literal to an array using a variable that holds the array name 从内部函数获取对象键名称? - Getting Object Key Name from inside function? 获取其中初始化/创建了全局对象的函数名称 - getting function name in which a Global object was initilized/created 在 JavaScript 中获取 object 变量名称 - Getting the object variable name in JavaScript 获取新对象的对象变量名称 - Getting the object variable name for the new object JavaScript中哪个对象持有“ <head> .. </head> “? - Which object in JavaScript holds “<head>..</head>”? 这是否可以设计一个 function 接受一个参数并返回一个 object 包含多个属性或功能 - Is this possible to design a function which takes a parameter and returns an object which holds multiple properties or functions
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM