Powiedzmy, że mam taką klasę
class Vector {
constructor(x,y) {
this.x = x
this.y = y
}
}
Jak mogę zrobić coś takiego
class Vector {
constructor() {
}
var x;
var y;
}
var v = new Vector()
v.x = 3
v.y = 4
Zasadniczo chcę zadeklarować moje zmienne poza konstruktorem. Zrobiłem trochę badań. Nic nie znaleziono
Odpowiedzi:
2 dla odpowiedzi № 1Chyba o tym mówisz Property Initialiazers
.
Twój kod może działać dobrze, jeśli go trochę zmodyfikujesz:
class Vector {
constructor() {}
x = 1;
y = 2;
}
var v = new Vector();
console.log(v.x, v.y); // 1 2
v.x = 3
v.y = 4
console.log(v.x, v.y); // 3 4
Pamiętaj tylko, że obecnie jest to plik stage-2
wniosek, więc nie będzie działać w żadnej przeglądarce po wyjęciu z pudełka.
Gdyby używasz babel możesz użyć transform-class-properties
chociaż wtyczka.
Gdyby nie używasz babel istnieje kilka alternatyw, z których możesz skorzystać - zostały one omówione w to pytanie.
1 dla odpowiedzi nr 2
Możesz przypisać właściwości po utworzeniu instancji:
class Vector {
constructor() {
this.x = null;
this.y = null;
}
}
let v = new Vector();
v.x = 1;
v.y = 2;
console.log(v.x, v.y); // 1 2
LUB
Możesz zdefiniować właściwości za pomocą get
i set
jak na przykład:
class Vector {
constructor() {
this.xValue = null;
this.yValue = null;
}
get x() {
return this.xValue;
}
set x(newVal) {
this.xValue = newVal;
}
get y() {
return this.yValue;
}
set y(newVal) {
this.yValue = newVal;
}
}
let v = new Vector();
v.x = 1;
v.y = 2;
console.log(v.x, v.y); // 1 2
Drugie podejście pozwala manipulować nową wartością przed jej ustawieniem.
Przykład:
class Vector {
constructor() {
this.xValue = null;
this.yValue = null;
}
get x() {
return this.xValue;
}
set x(newVal) {
this.xValue = `The value of "x" is ${newVal}.`;
}
get y() {
return this.yValue;
}
set y(newVal) {
this.yValue = `The value of "y" is ${newVal}.`;
}
}
let v = new Vector();
v.x = 1;
v.y = 2;
console.log(v.x, v.y); // The value of "x" is 1. The value of "y" is 2.