0
const j = Object.prototype.valueOf.apply

console.log(typeof j); // "function"
console.log(Object.prototype.valueOf.apply === j); // true

console.log(Object.prototype.valueOf.apply(3)); // WORKS
console.log(j(3)); // ERROR! TypeError: j is not a function

I found something weird situation in JS, about Function.prototype.apply and Function.prototype.call function. Without storing apply function in variable, it works. But when I store apply function to variable, it doesn't work.

What causes this weird situation?

lunuy lunuy
  • 429
  • 3
  • 7
  • That is what I get as error: "Uncaught TypeError: Function.prototype.apply called on incompatible undefined" see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Called_on_incompatible_type – Kai Lehmann May 25 '21 at 12:00
  • 2
    `apply` is not bound to `valueOf`. – Bergi May 25 '21 at 12:00
  • Typescript gives this additional error: `The 'this' context of type 'void' is not assignable to method's 'this' of type 'Function'.` – Kokodoko May 25 '21 at 12:04

1 Answers1

6

apply expects to be called as a method of a function. (i.e. someFunction.apply(...)). This would make the this value that function.

When you copy apply to j and then call j(); the this value is the default value (typically window if you are running in a browser).

That value is not a function.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335