In "use strict"
mode, this
in function should be [object Window]
rather than the object that calls the function in regular mode. But when I’m trying to proof of concept, it doesn’t work, I’m wondering something’s wrong with the ES6 extension in Visual Studio Code but I don’t know how to figure it out. Can someone help me? 😐
Here’s the code I used to test "use strict"
:
function name1() { document.querySelectorAll("p")[0].innerHTML += this; } function name2() { "use strict"; document.querySelectorAll("p")[0].innerHTML += this; } document.querySelectorAll("button")[0].addEventListener("click", name1); document.querySelectorAll("button")[1].addEventListener("click", name2);
Advertisement
Answer
With regard to this
, strict mode will mean that functions called without any calling context – unbound functions not on an object – will receive a this
of undefined
instead of the global object.
For example, you’d be able to see the different with the function below:
function fn() { // use strict here to see the difference console.log(this); } fn();
Strict mode has no effect on the this
of functions that are called with a calling context. Here, both buttons are being called with a calling context of the button, so the clicked button is the resulting this
inside the handlers, no matter whether strict mode is used or not.
Nothing to do with VSCode – this is how things’ll work anywhere.
function name1() { document.querySelectorAll("p")[0].innerHTML += this; } function name2() { "use strict"; document.querySelectorAll("p")[0].innerHTML += this; } document.querySelectorAll("button")[0].addEventListener("click", name1); document.querySelectorAll("button")[1].addEventListener("click", name2);
<p>p</p> <button>b1</button> <button>b2</button>
If you want to change the this
inside a particular click handler, you can
- use an arrow function instead of a
function
.bind
the function, eg.addEventListener("click", name1.bind(desiredThis));
- invoke the function inside instead of passing it, eg
.addEventListener("click", () => obj.name1());
will invoke with athis
ofobj