Public Trust
Public Trust

Reputation: 110

JavaScript Object Scope - using object variables within object methods

I'm trying to understand JavaScript object syntax. I have a canvas element that I'm drawing to, and I want to change the pattern I draw to it. I expect it to work like this:

pattern1 = {
    'x':0,
    'y':0,
    'draw': function() {
        context.clearRect(0,0,w,h);
        context.save();
        context.translate(this.x, this.y);
        context.fillText('Hello', 0, 0);
        context.restore();
        this.x += 1;
        this.y += 1;
    }
};

But this does not work. The 'x' and 'y' variables are not in the "this" scope. So instead of using this I refer to the object explicitly: 'pattern1.x' and 'pattern1.y'. But it seems like there should be a better way to do this.

I'm not so much looking for a "solution" here as an explanation. Thanks.

Upvotes: 0

Views: 38

Answers (1)

ozil
ozil

Reputation: 7117

pattern1 = function (){
    this.x=0;
    this.y=0;
    this.draw= function() {
        context.clearRect(0,0,w,h);
        context.save();
        context.translate(this.x, this.y);
        context.fillText('Hello', 0, 0);
        context.restore();
        this.x += 1;
        this.y += 1;
    }
};

var patObj=new pattern1 ();    // Function Calling
patObj.draw();

Upvotes: 1

Related Questions