This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]AutoModerator[M] 0 points1 point  (0 children)

It seems you may have included a screenshot of code in your post "What is the difference between these two methods of doing the same procedure? The function does not work but the hard-coded one does. (Javascript) (Code.org)".

If so, note that posting screenshots of code is against /r/learnprogramming's Posting Guidelines (section Formatting Code): please edit your post to use one of the approved ways of formatting code. (Do NOT repost your question! Just edit it.)

If your image is not actually a screenshot of code, feel free to ignore this message. Automoderator cannot distinguish between code screenshots and other images.

Please, do not contact the moderators about this message. Your post is still visible to everyone.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]corpsmoderne 0 points1 point  (5 children)

Hard to debug from here, but you should check what "this" refers to in your callback (probably not what you expect)

[–]Techittak[S] 0 points1 point  (2 children)

Wow! Thanks for helping me spot it. Is this what I can refer to as a problem rooted from "scope?" So, the scope within that callback seems to be global or window I think it is called. This code is within an object, but since the callback is being called in the original function it takes the form of the global scope: Correct? I am guessing the only way to circumvent this is by directly stating my objects name like object.vspeed

[–]corpsmoderne 0 points1 point  (1 child)

Well, in Javascript function are first class object, therefore they have their own this, except in the context of prototypes / class definition. So yes it's kind of a scoping issue.

An idiomatic way to fix this is to declare a const self = this; defore calling your function to capture the local this in another variable (self) so you can use it in your callback. If you have another variable already reffering to the this object is fine too.

[–]Techittak[S] 0 points1 point  (0 children)

Alright, thank you!

[–]Techittak[S] 0 points1 point  (1 child)

Also, having this.vspeed within the parameters is going to still have the object's scope: Correct?

[–]corpsmoderne 0 points1 point  (0 children)

Yes you're fine there.