[–] [deleted] 0 points 1 point 1 point (+1|-0) ago (edited ago)
[–] tragicwhale [S] 0 points 1 point 1 point (+1|-0) ago
Hey Rodrigo, thanks for the examples, those will definitely be in my notes and help clarify some things. Very much appreciate it.
[–] Cuddlefluff 0 points 3 points 3 points (+3|-0) ago
This is generally the object you called the function on
someObject.func()in this casethisrefers to thesomeObjectobject.However, this is not always the case, but that's the rule you should follow. If you call a function in a global scope (not on an object)
thisrefers towindow.The reason I say it's not "always the case" is because sometimes the context might be different, and
thisrefers an object that is not necessarily the one you called it on (for instance for some asynchronous methods), but what you'd "expect"thisto refer to. Sometimes you need to redirect thethisreference to something else, and that's done withsomeFunction.Call(whatEverYoudLikeTheThisReferenceToBeAssignedTo)JavaScript is very different than other object oriented languages in this case, because JavaScript is not an object oriented language (I know a lot of people will disagree with me on that, but it really isn't)
I don't know if I cleared anything up, or if I made things just harder to understand, so I'll just reiterate :
thisrefers to the object you called a function on. If you called a function in a global scope (not part of an object)thisrefers towindow. It's that simple.[–] tragicwhale [S] ago
I'm going to read your comment over and over but I feel like the portion where you talk about it refering to window helped. Thanks for your response.
[–] Cuddlefluff ago (edited ago)
I'm not any good at explaining things, but it's really quite easy once you "get" it. I have a long career of object oriented programming (C++, Java and C#), and
thisalso confused me a great deal in JavaScript in the beginning. It's not as intuitive and obvious as you'd expect. But it all boils down to whether or not you wrote a.-thiswould refer to the object on the left-hand side of the., If there is no.it would refer to the global scope akawindow. That's it, I don't know if I'm able to make it any clearer than that :P