简体   繁体   English

是否有对象的function.name之类的东西

[英]is there such thing as function.name for objects

So I was wondering if there is a way to use function.name but for objects. 所以我想知道是否有一种方法可以使用function.name而不是对象。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/name

What I mean by this is to have something like this: 我的意思是要拥有这样的东西:

function myFunction() {}

console.log(myFunction.name); // logs "myFunction"

// but like

var myObj = {};

console.log(myObj.name); // logs "myObj"

and if it is possible, how would it handle something like this? 如果可能的话,它将如何处理这样的事情?

var myObj = {};
var myObj2 = {};

console.log(myObj2.name); // logs "myObj" or "myObj2" or both?

Two things 两件事情

  1. Object don't have name property by default, unless you specify the same while defining the object, 默认情况下, Object没有name属性,除非您在定义对象时指定了相同的属性,

for example 例如

var myObj = {
  name : "myObj"
};
  1. In myObj2.name , myObj2 is not the name of the object, it is the name of reference (variable) to object. myObj2.namemyObj2不是对象的名称,而是对象的引用(变量)的名称。

Short answer? 简短的答案? No. 没有。

On the other hand, as you may know, global variables are part of window variable. 另一方面,您可能知道,全局变量是窗口变量的一部分。 Therefore, you could do something like: 因此,您可以执行以下操作:

function findName(obj, scope){
    if(scope === void 0){
        scope = window
    }
    for (prop in scope) {
        if(scope.hasOwnProperty(prop) && scope[prop] == obj){
            return prop
        }
    }
}

NOTE: This is extremly inefficent way to get variable name! 注意:这是获取变量名的极端无效的方法!

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

相关问题 IE中不支持function.name。 - function.name not supported in IE. 获取输入变量的名称(如 Function.name) - get name of input variable (like Function.name) 如何获取类似于 Function.name 的属性名称? - How to get an attribute name similar to Function.name? 如果 function 通过属性添加到 object,则 function.name 返回空字符串 - function.name returns empty string if the function is added to an object by property 使用Polyfilled Function.name的IE11 Javascript行为 - IE11 Javascript behavior with polyfilled Function.name Javascript function.prototype.constructor.name 和 function.name 的区别 - Javascript difference between function.prototype.constuctor.name and function.name 无法使用 node.js 在 VS Code 中更改 function.name - can't change function.name in VS Code with node.js 为什么在对象本身(例如Function.name)上定义Function属性,而在Function.prototype上定义方法? - Why do Function properties are defined on the object itself (e.g. Function.name), but methods - on Function.prototype? 在jQuery中,没有JS参与的函数名称本身就是东西吗? - In jQuery is there such thing as a function name natively with out JS engagement? 这是一个箭头 function 声明吗? 有这样的事吗? - Is this an arrow function declaration? Is there such a thing?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM