0

I have this snippet of code. I am very new to JavaScript, and I have an error in:

class X {
    constructor() {
      this.pick = -1;
      this.isClosed = false;
      this.pline = [];
    }

  add(mx, my) {
    pline.push(Point(mx,my));
  }
  
  draw() { 
    beginShape();
    for (let i = 0; i < pline.length; i++) {
        p = pline[i];
        vertex( p.x, p.y );
    }
    ... //ignore the rest for now

the issue I am getting is: X, line 14:ReferenceError: Can't find variable: pline

I am a little confused because I am initializing it as a class property, so I am not sure why it cannot be found in the draw function. Any help is highly appreciated.

Amin
  • 99
  • 5

3 Answers3

2

This is because you have scoped pline to this, so it must be this.pline.push.

Also, if you want to use this scope, it's best to use arrow function methods to maintain the scope. Example:

class clazz{
    constructor() {
        this.something = 1;
    }
    
    add = () => {
        
        console.log(this.something);
        
    };
}
Christian
  • 6,961
  • 10
  • 54
  • 82
2

pline refers to a variable (either local or global), not a property. If you want to access a property, then you must use this.pline. Although variables and properties seem the same, under the hood they are fairly different because of how JavaScript classes work (which is quite different from most languages).

Michael M.
  • 10,486
  • 9
  • 18
  • 34
1

in your add() function you are referring to "pline.push()", you need to use this.pline.push()