对类属性进行了更改,但不确定为什么会发生

时间:2019-03-22 18:49:57

标签: javascript class

我已经编写了一些简单的代码来更改类中的某些属性。.尽管代码不应更改名为this.patrons = []的数组,但当我通过console.log注销时,似乎正在更改它。 / p>

 class Library {
  constructor() {
    this.books = [];
    this.patrons = [];
    this.dailyFine = 0.1;

  }
  addBook(book) {
  // addd books to the  books array
   this.books.push(book);

  }
  addPatron(patron) {
    // add patrons to the patrons array
    this.patrons.push(patron);
  }

  chargeFines() {
    const now = new Date();

    const latePatrons = this.patrons.filter(patron => 
        (patron.currentBook !== null && patron.currentBook.dueDate < now)
    );
    console.log("nnn");
    console.log(this.patrons);
    for (let patron of latePatrons) {
        const dateDiff = new Date(now - patron.currentBook.dueDate);
        const daysLate = dateDiff.getDate();
        patron.balance += this.dailyFine * daysLate;
    }
}

据我对过滤器的了解,它不会更改原始数组,但在这种情况下,它会返回一个新数组latePatrons,因此,this.patrons []应该单独放置。

但是当我使用console.log时,似乎正在对其进行更改,因为它在输出中反映了这一点?

这是测试脚本

  <script>
  // our test code here
  const library = new Library();
  const book = new Book('Harry Potter and the Sorcerer\'s Stone', 'J.K. Rowling', '978-0439708180');
  const bookB = new Book('Art of fighting', 'Bruce Leee ', '556677');
  const patron = new Patron("Laurence Kite", "lawwz@hotmail.com");
  const patron2 = new Patron("Bruce Lee", "Lee@kungfu.com");
  library.addPatron(patron);
  library.addPatron(patron2);
  library.addBook(book);
  library.addBook(bookB);
  patron.checkOut(book);
  patron2.checkOut(bookB);
  console.log(patron);
  console.log(patron2);
  library.chargeFines();
  console.log(patron);
  console.log(patron2);
</script>

输出:

Patron {name: "Laurence Kite", email: "lawwz@hotmail.com", currentBook: Book, balance: 0}balance: 1.5currentBook: Book {title: "Harry Potter and the Sorcerer's Stone", author: "J.K. Rowling", isbn: "978-0439708180", _out: true, dueDate: Fri Mar 08 2019 18:43:12 GMT+0000 (Greenwich Mean Time), …}email: "lawwz@hotmail.com"name: "Laurence Kite"__proto__: Object
(index):27 Patron {name: "Bruce Lee", email: "Lee@kungfu.com", currentBook: Book, balance: 0}
Library.js:55 nnn
Library.js:56 (2) [Patron, Patron]0: Patron {name: "Laurence Kite", email: "lawwz@hotmail.com", currentBook: Book, balance: 1.5}1: Patron {name: "Bruce Lee", email: "Lee@kungfu.com", currentBook: Book, balance: 1.5}length: 2__proto__: Array(0)
(index):29 Patron {name: "Laurence Kite", email: "lawwz@hotmail.com", currentBook: Book, balance: 1.5}
(index):30 Patron {name: "Bruce Lee", email: "Lee@kungfu.com", currentBook: Book, balance: 1.5}

0 个答案:

没有答案