Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Module pattern and this

Tags:

javascript

I am using the module pattern for my JavaScript "classes". Is there any significant downside to declaring a var self outisde of the class I am returning and then setting it to this inside the class constructor so that I don't have to worry about the context switching when I don't want it to. In this small example it's probably unnecessary, this is just an example.

Example:

    var Seat = (function() {
      var self = null;
      function Seat(startX, startY, inputSeatNumber, inputTableNumber) {
        self = this;
        self.radius = 10;
        self.x = startX; self.y = startY;
        self.seatNumber = inputSeatNumber;
        self.tableNumber = inputTableNumber;
      }

      Seat.prototype.moveTo = function(newX, newY) {
        if(newX >= 0 && newY >= 0) {
          self.x = newX; self.y = newY;
        }
      };

      return Seat;
    })();

EDIT: example added

var SeatingChartView = (function() {
  function SeatingChartView(canvas_id, seatingChartController, seatForm) {
    this.stage = new createjs.Stage(canvas_id);
    this.controller = seatingChartController;
    this.seatForm = seatForm;

    this.disableRightClick(canvas_id);
  }

  SeatingChartView.prototype.render = function() {
    this.stage.update();
  }

  SeatingChartView.prototype.addSeat = function(newSeat) {
    var newCircle = new createjs.Shape();
    newCircle.graphics.beginFill("black").drawCircle(0, 0, 10);
    newCircle.x = newSeat.x;
    newCircle.y = newSeat.y;
    newCircle.seat = newSeat;
    newCircle.on('click', function(event) {
      if(event.nativeEvent.button == 2) {
        this.seatForm.open(event.currentTarget.seat);
      }
    });
    newCircle.on('pressmove', this.controller.moveSeat)
    this.stage.addChild(newCircle);
  }

  SeatingChartView.prototype.removeSeat = function(seat) {
    this.stage.children.forEach(function(child) {
      if(child.seat === seat) {
        this.stage.removeChild(child);
      }
    });
  }

  SeatingChartView.prototype.setBackground = function(imageLocation) {
    this.background = new createjs.Bitmap(imageLocation);
    window.setTimeout(function() {
      this.stage.canvas.width = this.background.image.width;
      this.stage.canvas.height = this.background.image.height;
      this.stage.addChild(this.background);
      this.stage.update();
    }.bind(this), 500);
  }

  SeatingChartView.prototype.disableRightClick = function(canvas_id) {
    $(function() {
      $('#' + canvas_id).bind('contextmenu', function(e) {
        return false;
      });
    });
  }

return SeatingChartView;
})();
like image 890
ThomYorkkke Avatar asked Aug 24 '26 08:08

ThomYorkkke


1 Answers

In that case every new instance of Seat will share the newest Self object since it is set in the constructor. You should avoid doing this.

like image 183
knpwrs Avatar answered Aug 26 '26 23:08

knpwrs