I essentially just want to assign the default value of a class variable to an empty array.
I've tried the following, but did not have any luck:
class Test {
constructor(myArray = []) {
this.myArray = myArray;
}
}
Obviously this doesn't work, as when I try to print Test.myArray, undefined is returned rather than an empty array.
CodePudding user response:
You are trying to access Prototype, your class is initialized correctly, just do:
class Test {
constructor(myArray = []) {
this.myArray = myArray;
}
}
const t = new Test();
console.log(t.myArray)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
new
keyword means, that you are creating a new instance of the Test class.