0

I'm new on JS developing, I'm trying to use OO Javascript using "classes", I have a class named "Timeblock", with it constructor:

var Timeblock = function(occupied, on, element) {
  this.occupied = occupied;
  this.on = on;
  this.room_id = 0;
  this.element= element;
}

I've created an object this way:

timeblock = new Timeblock(false, false, $('#element'));

Everything works at this point, now I'm trying to add a click event listener to the class constructor on its element var, I tried:

var Timeblock = function(occupied, on, element) {
  this.occupied = occupied;
  this.on = on;
  this.room_id = 0;
  this.element = element;

  timeblock = this;
  this.element.click(function() {
      timeblock.update();
  });
}

Timeblock.prototype.update = function() {
  if (!occupied) {
    this.element.addClass('on');
  }
}

When debugging in Chrome, I put a breakpoint on this.element.addClass('on'); inspecting the object I can read this.element: jQuery.fn.init[0] and I can't get it to work.

Even in console when I type this.element I get undefined, but if I type this.occupiedI get false

My question is, why I'm getting undefined? how can I make it work?, I've searched and searched but can't find any good material to study OO Javascript.

1 Answer 1

4
var Timeblock = function(occupied, on, element) {
  this.occupied = occupied;
  this.on = on;
  this.room_id = 0;
  this.element = element;

  var timeblock = this; // need var statement
  this.element.click(function() {
      timeblock.update();
  });
}

Timeblock.prototype.update = function() {
  if (!this.occupied) { // forgot this
    this.element.addClass('on');
  }
}

Two errors. I fixed them, and left comments explaining.

Sign up to request clarification or add additional context in comments.

2 Comments

Thaks, it works, but why the var statement is needed?
Because otherwise it becomes a global, and is overwritten every time you initialize a new Timeblock.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.