简体   繁体   English

有没有办法通过查找构造函数来获取类的名称

[英]Is there a way to get a classes' name through finding a constructor

I am trying to get a classes name through the name of a constructor in a class similar to what they have as the answer for this ask How to get a JavaScript object's class?我正在尝试通过 class 中的构造函数名称来获取类名称,类似于他们对此问题的答案如何获取 JavaScript 对象的 class?

What I want to do, is find the item with the id of 0 and get the second constructor of name我想要做的是找到id为 0 的项目并获取name的第二个构造函数

class item {
    constructor(id, name, price) {
        this.id = id
        this.name = name
        this.price = price
    }
const Bar = new item(0, "Candy bar", "$1") 
const Gum = new item(1, "Gum, "$.5")

I need to be able to grab, any id such in this case 1, and use it to find the item's name在这种情况下,我需要能够抓取任何 id,例如 1,并使用它来查找项目的名称

So I want to do something close to所以我想做一些接近

var thisItem = item.with.id = 1
console.log(thisItem.name)

You could just do that using Map it allows you to save the data with key and value like this您可以使用Map做到这一点,它允许您使用这样的keyvalue保存数据

and it has a lot of functionality that may help like has , get and so on它有很多可以帮助的功能,比如has , get等等

 const data = new Map(); data.set(1, {name: 'john', price: 145}); data.set(2, {name: 'taylor', price: 20}); if(data.has(1)){ console.log(data.get(1).name); } data.forEach((el) => { console.log(el); });

Sorry for all the confusion, @DaveNewton helped me figure it out对不起,@DaveNewton 帮我弄明白了

class item {
    constructor(id, name, price) {
        this.id = id
        this.name = name
        this.price = price
        items.push([id, name, price])
    }
}

i have this.push in the item class, and I can use the items[] now to sort through我在 class 项中有 this.push,我现在可以使用items[]进行排序

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM