Search code examples
javascriptcall

Javascript call() method


I understand this code works:

var links = document.querySelectorAll('div');
for (var i = 0; i < links.length; i++) {
    (function(){
        console.log(this);
    }).call(links[i]);
}

but why does this work:

var links = document.querySelectorAll('div');
for (var i = 0; i < links.length; i++) {
    console.log.call(this, links[i]);
}

isn't this supposed to be window object in context of calling every iteration?


Solution

  • It's no different from calling

    var links = document.querySelectorAll('div');
    for (var i = 0; i < links.length; i++) {
        console.log(links[i]);
    }
    

    You are right, in this scope the this keyword is bound to the window object, if you run the snippet bellow, you can see that I append a new property SomeUniqueValue to the window object which becomes accessible inside the scope of the look when using the call function.

    Now, if you wrap that block inside a function, you can see the the this keyword is limited to the scope of the calling block, hence in the last example only the span gets logged to the console.

    var links = document.querySelectorAll('div');
    for (var i = 0; i < links.length; i++) {
        console.log(links[i]);
    }
    
    window.SomeUniqueValue = "WAWAWIWA";
    for (var i = 0; i < links.length; i++) {
        console.log.call(this, SomeUniqueValue);
    }
    
    var someFunction = function() {
      'use strict';
      var links = document.querySelectorAll('span');
      for (var i = 0; i < links.length; i++) {
          console.log.call(this, links[i]);
      }
    }
    
    someFunction();
    <div>This</div>
    <div>Works</div>
    <div>Fine</div>
    <span>Inner Scope</span>