Tuesday, May 2, 2017

JavaScript Scope & 'this' keyword

There are also problems that we run into when dealing with the this value, for instance if I do this, even inside the same function the scope can be changed and the this value can be changed:


var nav = document.querySelector('.nav'); // <nav class="nav">
var toggleNav = function () {
  console.log(this); // <nav> element
  setTimeout(function () {
    console.log(this); // [object Window]
  }, 1000);
};
nav.addEventListener('click', toggleNav, false);

So what’s happened here? We’ve created new scope which is not invoked from our event handler, so it defaults to the window Object as expected.

@reference_1_toddmotto.com

An anonymous function this will refer to the window object on the global scope.

@reference_2_stackoverflow

this
@reference_3_mozilla

No comments:

Post a Comment