0

one quick question.

I know i can make a class and do it with "this", keyword, but can i somehow do it alternatively via prototypical inheritance?

Example:

const obj1 = {
    name: "Admin",
    log: () => console.log(obj1.name),
};

I make a object with a name and a method that console.logs obj1's name

const obj2 = {
    name: "Moderator",
};

obj2.__proto__ = obj1;

So i make another object that only has a name, without log method, and i do prototypical inheritance so obj2 now has access to that method even if it's not created with it.

obj2.log();

// output: "Admin"

How can i bind log method to the object that calls it, so if i use it as obj2 through prototypical inheritance, it will log obj2's name "Moderator"

  • 1
    Don't use `__proto__`, create an object with `Object.create()` and pass in the prototype to use. – Pointy Feb 13 '23 at 15:52

1 Answers1

1

Use a regular function instead of an arrow function and access this.name.

const obj1 = {
    name: "Admin",
    log() {
      console.log(this.name);
    }
};
const obj2 = {
    name: "Moderator",
};
obj2.__proto__ = obj1;
obj2.log();
Unmitigated
  • 76,500
  • 11
  • 62
  • 80