Class 对象重叠

Class object overlapping

我仍在努力学习,我正在尝试将一组演员添加到电影中 class,我做到了,但我仍然有问题,因为如果你添加另一个演员,最后一个演员就会消失,我尝试了一个循环,但我什么也做不了。

class Movie {
    constructor(title,year,duration){
        this.title = title;
        this.year = year;
        this.duration = duration;
    }

    addCast(actors){
        this.actors = actors
    }
}     
class Actor {
    constructor(name,age)
    {  
        this.name = name;
        this.age = age;
    }
}

const terminator = new Movie('Terminator I', 1985, 60);
const arnold = new Actor('Arnold Schwarzenegger', 50);
const otherCast = [
    new Actor('Paul Winfield', 50),
    new Actor('Michael Biehn', 50),
    new Actor('Linda Hamilton', 50)
];
//From here it can not be modified
    let movieOne = new Movie("Kong","2018","2h30m");
    let movieTwo = new Movie("Joker","2019","2h03m");
    let movieThree = new Movie("John Wick 3", "2019", "1h49m");
    terminator.addCast(arnold);
    terminator.addCast(otherCast);
//To here it can not be modified
    console.log({movieOne,movieTwo,movieThree,terminator});

看到了吗?阿诺德也应该在演员中,但事实并非如此!提前感谢您的帮助。

另一件事,这是练习,我不能修改我评论的行。

你有

addCast(actors){
    this.actors = actors
}

这不会将传递的 actor 数组 添加到实例上的 actors - 它 替换 实例的 actors 与传递的参数。调用 addCast 将导致 actors 上以前存在的任何内容丢失。

为了帮助减少错误,它可以帮助适当地命名方法 - 对于这样的逻辑,我将其称为 setCast,而不是 addCast

如果您想添加到现有演员阵容的末尾,并且您不确定参数是要添加的单个演员还是要添加的演员数组,请使用:

  addCast(actorOrActors) {
    if (Array.isArray(actorOrActors)) {
      this.actors.push(...actorOrActors);
    } else {
      this.actors.push(actorOrActors);
    }
  }

class Movie {
  constructor(title, year, duration) {
    this.title = title;
    this.year = year;
    this.duration = duration;
    this.actors = [];
  }

  addCast(actorOrActors) {
    if (Array.isArray(actorOrActors)) {
      this.actors.push(...actorOrActors);
    } else {
      this.actors.push(actorOrActors);
    }
  }
}
class Actor {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

const terminator = new Movie('Terminator I', 1985, 60);
const arnold = new Actor('Arnold Schwarzenegger', 50);
const otherCast = [
  new Actor('Paul Winfield', 50),
  new Actor('Michael Biehn', 50),
  new Actor('Linda Hamilton', 50)
];
//From here it can not be modified
let movieOne = new Movie("Kong", "2018", "2h30m");
let movieTwo = new Movie("Joker", "2019", "2h03m");
let movieThree = new Movie("John Wick 3", "2019", "1h49m");
terminator.addCast(arnold);
terminator.addCast(otherCast);
//To here it can not be modified
console.log({
  movieOne,
  movieTwo,
  movieThree,
  terminator
});

这是因为在您的 addCast() 方法中,每次调用它时,您都会替换以前的值而不是附加它

您用第二次 addActors 调用覆盖了 arnold。 一次只能将一个演员添加到演员数组中。

class Movie {
constructor(title,year,duration){
    this.title = title;
    this.year = year;
    this.duration = duration;
    this.actors = [];
}


addCast(actor){
    this.actors.push(actor);
}

terminator.addCast(arnold);
terminator.addCast(otherCast[0]);
terminator.addCast(otherCast[1]);
terminator.addCast(otherCast[2]);