0

I've tried out this code and it doesn't work:

function benchmark(n) {
  let sum = 0;
  for(let i = 1; i <= n; i++) sum += i;
  return sum;
}

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;
  };
}

obj = {};
benchmark.call(obj);
trace(obj, "benchmark");
obj.benchmark(1000000);
obj["benchmark"](1000000);

The error is Uncaught TypeError: Cannot read properties of undefined (reading 'apply') at Object.o.<computed> [as benchmark]. This error happens at let result = original.apply(this, args); because it was indicated by the error line number in the Console.

This error is not resolved if I use apply() in benchmark.call(obj):

benchmark.apply(obj);

This error is only resolved if I use this:

obj.benchmark = benchmark;

I extract this from "JavaScript - The Definitive Guide":

call() and apply() allow you to indirectly invoke a function as if it were a method of some other object. The first argument to both call() and apply() is the object on which the function is to be invoked; this argument is the invocation context and becomes the value of the this keyword within the body of the function. To invoke the function f() as a method of the object o (passing no arguments), you could use either call() or apply():

f.call(o);
f.apply(o);

So, why wouldn't benchmark.call(obj); or benchmark.apply(obj); work in my code?

maxloo
  • 453
  • 2
  • 12
  • 3
    `obj` does not have a `benchmark` function. Thus `let original = o[m]` (where `m == 'benchmark'`) will leave `original` as `undefined` and you can't call `apply` on undefined – derpirscher Nov 10 '21 at 08:03
  • `call()` and `apply()` take *the value of `this` as first parameter*. To pass the first parameter *to the function` you are calling `.call()` on, you need to pass a *second* argument to it. For `.apply()` you need to pass an array-like as second argument. – VLAZ Nov 10 '21 at 08:04

0 Answers0