0

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.

Public Trust
  • 90
  • 1
  • 8
  • In JS `this` is set depending on how you call a function. How do you call your function? If you use `pattern1.draw()` then `this` should refer to `pattern1`. – nnnnnn Mar 24 '15 at 06:52
  • See this for an explanation of how `this` works in javascript: http://stackoverflow.com/questions/13441307/how-does-the-this-keyword-in-javascript-act-within-an-object-literal/13441628#13441628 – slebetman Mar 24 '15 at 08:01
  • I did not have the vocabulary to ask this question correctly. The information I was really looking for I found at http://stackoverflow.com/questions/1600130/javascript-advantages-of-object-literal – Public Trust Mar 30 '15 at 06:46

1 Answers1

1
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();
ozil
  • 6,930
  • 9
  • 33
  • 56