1

I am currently learning JavaScript and I thought that I understood functions. Apparently not. I thought that, in the following code, first argument of apply() call, which is this, would evaluate to global object.

var x = 100;

function trace(o, m) {
  let original = o[m];
  o[m] = function(...args) {
    console.log(new Date(), "Entering:", m);
    let result = original.apply(this, args);
    console.log(new Date(), "Exiting:", m);
    return result;
  };
}

let obj = {
  x: 10,
  m: function() {
    console.log('X is: ', this.x);
  }
}

trace(obj, 'm');
obj.m();

Can somebody clarify why that's not the case?

ponury-kostek
  • 7,824
  • 4
  • 23
  • 31
AlexBor
  • 151
  • 2
  • 12
  • 1
    `this` is late-bound. You're setting a property of `obj` and calling it in the context of that object. – Dave Newton Nov 25 '21 at 19:06
  • 1
    "*I thought that [the `this` that is passed to `apply`] would evaluate to global object.*" - can you explain *why* you thought that? Otherwise we cannot clarify where you went wrong. – Bergi Nov 25 '21 at 19:34

0 Answers0