Vael Victus
Vael Victus

Reputation: 4122

What are all the properties available on a Component object in Svelte?

import ItemPanel from '../Panel/ItemPanel.svelte';

If I log console.log(ItemPanel), I get the class definition:

class ItemPanel extends SvelteComponentDev {
        constructor(options) {
            super(options);

            init(
                this,
                options
...

But if I console.log(ItemPanel.name), I simply get "ItemPanel" returned to me.

I use the panel's name in a modal component that receives components to open, and this is how I've been IDing them for special functionality. But then I realized that I lose that functionality on production build because I'm tensor()ing and that changes the component's name in production. I'm hoping to log all properties to see if there's one that sticks between both dev and production mode.

Upvotes: 1

Views: 605

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074694

I don't think this is a Svelte-specific question, though of course I could be mistaken.

Answering what you actually asked, you can get the properties of an object (including a function object) via Object.getOwnPropertyNames (for the ones with string names) and Object.getOwnPropertySymbols (for the ones with Symbol names). (In contrast, Object.keys only gives you a subset of what getOwnPropertyNames gives you: the names of own enumerable properties with string names. [getOwnPropertyNames includes non-enumerable ones.]) To get inherited properties, use Object.getPrototypeOf and then use the first two functions again. Rinse, repeat until you reach Object.prototype.

But getting to your underlying requirement:

ItemPanel in your code is a constructor function. Functions get their names by how they're defined. A constructor function created via a named class declaration or expression (yours looks like a declaration) gets its name from the name given for the class. The name property of a function gives the name of the function.

If you're minifying the code in some way such that name is no longer what you're looking for, and you need some similar unique identifier, you can add one using a static field:

class ItemPanel extends SvelteComponentDev {
    static id = "ItemPanel";
    // ...
}

Of course, that means repeating yourself.

But stepping back a step:

I use the panel's name in a modal component that receives components to open...

In that situation I'd use the actual function rather than its name.

Upvotes: 1

Related Questions