0

Lets say that I have a class like this

class Vector {
    constructor(x,y) {
        this.x = x
        this.y = y
    }
}

How can i do something like this

class Vector {
    constructor() {
    }
    var x;
    var y;
}
var v = new Vector()
v.x = 3
v.y = 4

I basically want to declare my variables outside the constructor. Done some research. Found nothing

Blaze349
  • 429
  • 1
  • 5
  • 16

2 Answers2

3

I guess you are talking about Property Initialiazers.

Your code could work fine if you modify it a little:

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

Just keep in mind that this is currently a stage-2 proposal, so it won't work in any browser out of the box.

If you are using babel you can use transform-class-properties plugin though.

If you are not using babel there are some alternatives that you could use - they have been discussed in this question.

Community
  • 1
  • 1
biphobe
  • 4,525
  • 3
  • 35
  • 46
1

You can assign the properties after the instance is created:

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

OR

You can define the properties with get and set like so:

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

The second approach lets you manipulate the new value before setting it.

Example:

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.
Ricky Ruiz
  • 25,455
  • 6
  • 44
  • 53