0

I'm using draw2d js library. I have the following code that creates a rectangle on the canvas.

 var rect = new draw2d.shape.basic.Rectangle({x:20,y:30});
 rect.on("click", function(){
     //var that = this;
    alert("test");
// I'm trying to access rect using this keyword but its not working
    var c = new draw2d.Connection();
    this.createPort('hybrid'); // adds a port on the rectangle



});

I'm trying to access rect using this keyword but its not working

Thanks!

user2516083
  • 13
  • 1
  • 1
  • "its not working" probably wont get you very far here. What exactly is happening? – Jud Apr 16 '15 at 17:11

1 Answers1

0

this in that context does not refer to rect, but instead refers to the anonymous function you provided to on:

function(){
  alert("test");
  var c = new draw2d.Connection();
  this.createPort('hybrid'); // adds a port on the rectangle
} // => This is what `this` refers to.

You can just reference rect directly:

var rect = new draw2d.shape.basic.Rectangle({x:20,y:30});
rect.on("click", function(){
  alert("test");
  var c = new draw2d.Connection();
  rect.createPort('hybrid'); // adds a port on the rectangle
});

this is a fairly tricky point of JavaScript. I'd recommend reading Mozilla's guide to grok it better.

fny
  • 31,255
  • 16
  • 96
  • 127