We have a class which has a private array.
class BookService{
private booksList: Book[];
constructor (){
this.booksList = [
new Book('Tales', true),
new Book('Novels', false),
new Book('Dictionary', false)
];
}
getBooks(){
return this.booksList;
}
}
class Book{
constructor ( public name: string, public isRead: boolean ){}
}
export const bookService = new BookService();
Also we have an implementation.
import {bookService} from './book-service';
//get copy of original array which is not by reference
let books: any = bookService.getBooks().slice(0);
//log local array
console.log(books);
// modify local array
books[1].isRead = true;
//log original array
console.log(bookService.getBooks());
We got the copy of origin array. Then we modified local array ( copy of the origin array ). The we got origin array which was modified.
I can't understand why origin private array have been modified?
If I modify getBooks to
getBooks(){
return this.booksList.slice(0);
}
it won't help.
If I modify getBooks using the lodash method _.cloneDeep Method description
getBooks(){
return _.cloneDeep(this.booksList);
}
the original array won't be modified. Why? How to avoid mistakes which relate to this kind of situations?