• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Question about JavaScript scope for call method

#1
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
var forEach = function (array, callback, scope) {
 for (var i = 0; i < array.length; i++) {
   callback.call(scope, i, array[i]); // passes back stuff we need
 }
};

// Usage:
// optionally change the scope as final parameter too, like ECMA5
var myNodeList = document.querySelectorAll('li');
forEach(myNodeList, function (index, value) {
   console.log(index, value); // passes index + value back!
});

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');
$('#something', scope).whatever();

But I don't know about the other code.
Reply

#2
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
Reply

#3
(11-11-2017, 03:38 PM)ivantcholakov Wrote: 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

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>
<html>
<body>

<h2 class="example">A heading with class="example"</h2>
<p class="example">A <span>paragraph</span> with <span>class="example"</span>.</p>

<button onclick="myFunction()">Try it</button>

<script>

var forEach = function (array, callback, scope) {
 for (var i = 0; i < array.length; i++) {
   callback.call(scope, i, array[i]);
 }
};

function myFunction() {
    var whatever = 'y';
   var all = document.querySelectorAll(".example > span:first-of-type");
    forEach(all, function (index, value) {
      value.style.color = "red";
      console.log(whatever);
    });
}

</script>

</body>
</html>
Reply

#4
Code:
function myFunction() {
    var whatever = 'y';
    var all = document.querySelectorAll(".example > span:first-of-type");
    forEach(
        all,
        function (index, value) {
            value.style.color = "red";
            console.log(whatever);
        },
        whatever  // <--- Here
    );
}
Reply

#5
Got it. Within the actual callback body, the passed scope is to be accessed by *this*.

Code:
<button onclick="myFunction()">Try it</button>
<script>

var forEach = function (array, callback, scope) {

    for (var i = 0; i < array.length; i++) {
        callback.call(scope, i, array[i]);
    }
};

var scope_1 = { 'color': 'red' };
var scope_2 = { 'color': 'blue' };

function myFunction() {

    var scope_3 = { 'color': 'green' };
    var scope_4 = { 'color': 'yellow' };

    var all = document.querySelectorAll(".ui.top.attached.stackable.fluid.four.item.menu > a");

    forEach(
        all,
        function (index, value) {

            value.style.color = this.color;
        },
        scope_1 // Try here scope_2, scope_3, scope_4, colors would be different.
    );
}

</script>
Reply

#6
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.
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


Users browsing this thread:
1 Guest(s)


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2017 MyBB Group.