Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
"JavaScript - La guía definitiva" - "Los métodos call() y apply()"

He probado este código y no funciona:

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

El error es Uncaught TypeError: Cannot read properties of undefined (reading 'apply') at Object.o.<computed> [as benchmark] . Este error ocurre en let result = original.apply(this, args); porque estaba indicado por el número de línea de error en la Consola.

Este error no se resuelve si uso apply() en benchmark.call(obj) :

 benchmark.apply(obj);

Este error solo se resuelve si uso esto:

 obj.benchmark = benchmark;

Extraigo esto de "JavaScript - The Definitive Guide":

call() y apply() le permiten invocar indirectamente una función como si fuera un método de algún otro objeto. El primer argumento tanto para call() como para apply() es el objeto en el que se invocará la función; este argumento es el contexto de invocación y se convierte en el valor de la palabra clave this dentro del cuerpo de la función. Para invocar la función f() como un método del objeto o (sin pasar argumentos), puede usar call() o apply():

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

Entonces, ¿por qué no haría benchmark.call(obj); o benchmark.apply(obj); trabajar en mi código?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!