0

If I have a class with a constructor and in the constructor an array with objects and I want an object method to edit the values of the objects, it gets kind of messy.

This is what I'm kind of aiming for:

class SomeClass {
  constructor() {
    this.o = [
      {
        name: "John",
        changeName: () => {
          this.name = "Mike";
        },
      },
    ];
  }
}

SomeClass.o[0].changeName();

But that doesn't work because the this refers to the class and not the object.

0

1 Answer 1

1

First of all, you need to create an instance with new if you want the constructor to run.

Don't use arrow functions when you want this to refer to the object you called the method on.

So correct like this:

class SomeClass {
  constructor() {
    this.o = [
      {
        name: "John",
        changeName() { // not an arrow function
          this.name = "Mike";
        },
      },
    ];
  }
}

let obj = new SomeClass(); // use `new`

obj.o[0].changeName();

console.log(obj.o[0].name);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.