0

https://www.w3schools.com/graphics/tryit.asp?filename=trygame_canvas

I was looking at the js code from the tutorial in the link above, I understand mostly what's happening except for the line

this.context = this.canvas.getContext("2d");

Where does this.context come from? surely the word "this" is referring to the myGameArea object and then context is suppose to be some property of myGameArea, but it hasn't been defined. Any help would be greatly appreciated!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
tiggybits
  • 119
  • 1
  • 9
  • 2
    That line is defining `.context`. – melpomene Jan 12 '18 at 17:24
  • 1
    You're correct in that 'this' refers to myGameArea (which is an object). Objects can be expanded dynamically in Javascript. The line you mention is actually defining myGameArea.context. –  Jan 12 '18 at 17:26
  • Have a look at [this answer](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work/3127440#3127440) – bmceldowney Jan 12 '18 at 17:27

2 Answers2

1

That line is precisely defining the context property. Once you have an object, you can add properties to it that way: this.context = ....

I recommend you to take a look to this link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects Will for sure explain many things.

elbecita
  • 2,616
  • 19
  • 28
0

In loosely typed languages you are able to define properties of objects on runtime. It's pretty magic and allows for some pretty crazy stuff.

All that line does is set the context property to this.canvas.getContext("2d").

PHP works in a similiar way :)

ExohJosh
  • 1,832
  • 16
  • 22