简体   繁体   中英

How to edit values of an object inside an array inside a class in JavaScript?

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.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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