Skip to content
Advertisement

If a strict mode function is executed using function invocation, its ‘this’ value will be undefined

I’m getting the following warning when using jshint. Why?

If a strict mode function is executed using function invocation, its ‘this’ value will be undefined.

function demo() {
    'use strict';

    document.querySelector('#demo').addEventListener('click', test);

    function test() {
        console.log(this);
    }
}

Advertisement

Answer

Rather than try to suppress the warning, it’s better to address the root cause.

Use of this can be confusing, and the value of this can unexpectedly change when refactoring code. Your code will be easier to read and maintain if you explicitly pass parameters.

The parameter passed to the test() callback is the Event object for the click:

function demo() {
   'use strict';
   function test(event) {
      console.log('You clicked on:', event.target.outerHTML); 
      }
   document.querySelector('#demo').addEventListener('click', test);
   }

demo();

Console log output will be something like:
You clicked on: <h1 id="demo">Click Me</h1>

The Event object tells you the target element that the user clicked:
https://developer.mozilla.org/en-US/docs/Web/API/Event/target


Click Me

Fiddle with the code:
https://jsfiddle.net/24epdxbz/2

From yehudakatz:

The ECMAScript 5 spec says that undefined is (almost) always passed, but that the function being called should change its thisValue to the global object when not in strict mode. This allows strict mode callers to avoid breaking existing non-strict-mode libraries.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement