Question about JavaScript scope for call method |
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-fo...list-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.
As far as I can understand it is an object type, and usually it is assigned to **this**
https://stackoverflow.com/questions/5044...on-binding (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>
Code: function myFunction() {
11-11-2017, 04:51 PM
(This post was last modified: 11-11-2017, 08:39 PM by ivantcholakov. Edit Reason: a minor correction )
Got it. Within the actual callback body, the passed scope is to be accessed by *this*.
Code: <button onclick="myFunction()">Try it</button>
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.
|
Welcome Guest, Not a member yet? Register Sign In |