class MyClass {
constructor() {
this.points = [];
// I need to call this after the components are mounted
// So keeping the setup separate
this.setupMyClass();
}
setupMyClass() {
let {points} = this;
points = [...points, {x: 20, y:20}];
// ugly code
// need to repeat 'this.' everytime I use the variable
// this.points = [...this.points, {x: 20, y: 20}];
console.log('points', points);
console.log('this.points', this.points);
}
}
myClassInstance = new MyClass();
JSFiddle在这里
输出:
points: [{..}]
this.points: []
我认为数组是按引用发送的,而其他值是按值复制的。这个答案支持相同的。这里发生了什么事?
我需要以MyClass
简洁的方式访问变量,我该怎么做?