Search code examples
javascriptdraw2d

nested this pointer in javascript


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!


Solution

  • 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.