Question about JavaScript scope for call method - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: General (https://forum.codeigniter.com/forumdisplay.php?fid=1) +--- Forum: Lounge (https://forum.codeigniter.com/forumdisplay.php?fid=3) +--- Thread: Question about JavaScript scope for call method (/showthread.php?tid=69378) |
Question about JavaScript scope for call method - skunkbad - 11-11-2017 I'm reading about using plain JavaScript instead of jQuery, and came across an article on looping through elements that are in a node list. This is that article: https://toddmotto.com/ditch-the-array-foreach-call-nodelist-hack/ At the end, there is a recommendation to do the following: Code: // forEach method, could be shipped as part of an Object Literal/Module I see the comment regarding scope, but looking around the internet cannot find what this scope variable is all about. Can somebody explain about this scope? I know what scope is in jquery when I do something like this: Code: var scope = $('#container'); But I don't know about the other code. RE: Question about JavaScript scope for call method - ivantcholakov - 11-11-2017 As far as I can understand it is an object type, and usually it is assigned to **this** https://stackoverflow.com/questions/5044807/passing-scope-to-callback-function-binding RE: Question about JavaScript scope for call method - skunkbad - 11-11-2017 (11-11-2017, 02:38 PM)ivantcholakov Wrote: As far as I can understand it is an object type, and usually it is assigned to **this** So I guess it's sort of injecting in access to the local vars/functions. If callback.call() has the scope of "this", then the anonymous function has direct access to myNodeList. Is that right? -- Edit -- That's not right, because if you take a look at this code, the whatever var is accessible even without the scope of "this". Code: <!DOCTYPE html> RE: Question about JavaScript scope for call method - ivantcholakov - 11-11-2017 Code: function myFunction() { RE: Question about JavaScript scope for call method - ivantcholakov - 11-11-2017 Got it. Within the actual callback body, the passed scope is to be accessed by *this*. Code: <button onclick="myFunction()">Try it</button> RE: Question about JavaScript scope for call method - skunkbad - 11-12-2017 Well, I did learn something interesting. Today I was working on a script that utilized a callback that was very similar to this one. The code that was calling the callback was trying to pass a variable to be used by the callback, but without adding the scope variables the callback just said the variable was undefined. By chance I added the scope variables and it started working. |