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,92772 gold badges63 silver badges135 bronze badges
asked Jan 12, 2018 at 17:22
3
  • 2
    That line is defining .context. Commented Jan 12, 2018 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. Commented Jan 12, 2018 at 17:26
  • Have a look at this answer Commented Jan 12, 2018 at 17:27

2 Answers 2

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.

answered Jan 12, 2018 at 17:27
Sign up to request clarification or add additional context in comments.

Comments

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 :)

answered Jan 12, 2018 at 17:27

1 Comment

hmm ok! So context is still a property of myGameArea and can be accessed as myGameArea.context ?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.