Asd20752
Asd20752

Reputation: 333

Undefined object inside object when accessing with Object function

I am trying to change the value of "selectedArea" to the values I get from the mouse. Whenever I try to do so I get "Uncaught TypeError: Cannot read property 'start' of undefined". (mouseDown()) Probably an easy solution, just that I can not see it(quite new to javascript).

var areaSelection = {
mouseisDown: false,
selectedArea: {
    start: { x: 0, y: 0 },
    end: { x: 0, y: 0 }
},
initialize: function () {
    canvasSource.addEventListener("mousedown", this.mouseDown);
    canvasSource.addEventListener("mousemove", this.mouseMove);
    canvasSource.addEventListener("mouseup", this.mouseUp);
},
mouseDown: function (event) {
    if (!this.mouseisDown) {
        this.selectedArea.start.x = event.clientX;
        this.selectedArea.start.y = event.clientY;
    }
},
mouseMove: function (event) {
    if (this.mouseisDown) {
        var x = this.selectedArea.start.x;
        var y = this.selectedArea.start.y;
        var width = event.clientX - x;
        var height = event.clientY - y;
        drawOverlay(x, y, width, height);
    }
},
mouseUp: function (event) {
    if (this.mouseisDown) {
        this.selectedArea.end.x = event.clientX;
        this.selectedArea.end.y = event.clientY;
    }
}

};

Upvotes: 0

Views: 81

Answers (2)

dsh
dsh

Reputation: 12234

Depending on how you call the function, this will not be the object you expected. The this keyword is different in Javascript from other languages (eg Java, C++).

https://stackoverflow.com/a/3127440/1172714

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Upvotes: 0

Sebastian Nette
Sebastian Nette

Reputation: 7832

You are missing the correct context in which the function is called:

canvasSource.addEventListener("mousedown", this.mouseDown.bind(this));

If you don't bind the context then the this inside the listener refers to the clicked element, which is the canvas.

Upvotes: 1

Related Questions