This. uses

So iv been watching Coding Trains videos and he uses "this." a lot. But i don't understand how they work or are used. If someone could explain it for me that would be great.

Tagged:

Answers

  • edited August 2017 Answer ✓

    this. refers to a variable that is a part of an object. In my example below, inside my Bubble function I use this. to declare variables and make functions. These functions and variables are a part of the Bubble function. I can also call these variables and functions outside of the Bubble function. I'm sure there's more to it than that. Hopefully my example shows some ways in which this. is used.

    var bubbles = [];
    
    function setup() {
      createCanvas(400, 400);
    }
    
    function mousePressed() {
      append(bubbles, new Bubble(mouseX, mouseY));
    
    }
    
    function draw() {
      background(20, 20, 150);
      for (i = 0; i < bubbles.length; i++) {
        bubbles[i].display();
        bubbles[i].move();
        if (bubbles[i].x > width) {
          bubbles[i].wrap();
          bubbles[i].active = true;
        }
        if (bubbles[i].active === true) {
          console.log("bubble " + i + " = " + bubbles[i].x);
          bubbles[i].active = false;
        }
      }
    }
    
    function Bubble(x, y) {
      this.x = x;
      this.y = y;
      this.r = 25;
      this.yspeed = 1;
      this.active = false;
    
      this.move = function() {
        this.y = this.y - this.yspeed;
      }
      this.wrap = function() {
        this.y = height;
      }
      this.display = function() {
        fill(170, 223, 250);
        ellipse(this.x, this.y, this.r, this.r);
      }
    }
    
Sign In or Register to comment.