nevidev
nevidev

Reputation: 143

JS how to find the name of an object using "this" keyword?

i have an object named dogs:

const dogs = {
   name: "Murch",
   age: 8,
   says(){
     console.log(`My name is ${this.name}.`);
   }
};

Question is: How can i prints "dogs" using "this" keyword?

For example, if i

console.log(typeof this);

i get "object" but i want to name of the object.

Upvotes: 0

Views: 212

Answers (1)

Quentin
Quentin

Reputation: 943209

You can't get the variable to which an object is assigned.

It might be assigned to multiple variables or to none at all.

const dogs = {
   name: "Murch",
   age: 8,
   says(){
     console.log(`My name is ${this.name}.`);
   }
};

const cats = dogs;

cats.says();

({
   name: "Murch",
   age: 8,
   says(){
     console.log(`My name is ${this.name}.`);
   }
}).says();

Under some circumstances you can search places where an object might be a assigned and look for a match, but const variables are not one of those places.

const dogs = {
  name: "Murch",
  age: 8,
  says() {
    console.log(`My name is ${this.name}.`);
  },
  findme() {
    const match = Object.entries(animals).filter(([key, value]) => value === this).pop();
    if (match) console.log(match[0]);
  }
};

const animals = {
  dogs,
  cats: null,
  bats: null,
  rabbits: null
};

dogs.findme();

Upvotes: 1

Related Questions