- is seen in a book, and then the confusion arises. The code is as follows:
- function definition class of ES5
//
class Stack {
constructor() {
this.items = [];
}
push(element) {
this.items.push(element);
}
pop() {
return this.items.pop();
}
//
}
< H2 > question < / H2 >this is the explanation in the book:
- ES5
in ES5 we declare a private items variable that can only be accessed by Stack functions or classes. However, this method creates a copy of the items variable for each instance of each
class. Therefore, if you want to create multiple Stack instances, it is not quite appropriate.The
- ES6
variable items is public. ES6"s classes are prototype-based. Although prototype-based classes save more memory than function-based classes and are more suitable for creating to build multiple instances, you cannot declare private properties (variables) or methods.
- ES5 says that a copy of the items variable is created for each instance, so why is it not appropriate to create multiple Stack instances?
- but isn"t ES6 defining an items, with a constructor equivalent to creating an items variable for each instance? Why is it appropriate to create multiple instances? What is the advantage of this over ES5"s copy of the items variable?
(it is clear that prototype-based classes save more memory and are more suitable for creating multiple instances than function-based classes. )