0

Recently I noticed that there is not a difference between these two snippets.

function step() {
  if (!this.counter) this.counter = 0;
  return this.counter++;
}

console.log(step()); // -> 0
console.log(step()); // -> 1
console.log(step()); // -> 2
function step() {
  if (!this.counter) this.counter = 0;
  return this.counter++;
}

step.counter = 10;

console.log(step()); // -> 0
console.log(step()); // -> 1
console.log(step()); // -> 2

Why does setting a function property not affect it's this?

kalkronline
  • 459
  • 2
  • 12
  • `this` is not the function object. Never has been. [How does the "this" keyword work?](https://stackoverflow.com/q/3127429) – VLAZ Jun 13 '22 at 15:58
  • Believe it or not, but in your case `this` is equal to `window`. You are setting a global property using `this`. This is tricky, for this reason it has been disabled in modern versions of JavaScript when using `use strict` – Christian Vincenzo Traina Jun 13 '22 at 16:01

0 Answers0