-1

I was writing some JS code for a project, and I encountered this behavior:

// example 1:
var x = {a: 1, b: 2};
console.log(x.hasOwnProperty('a')); // outputs true, as it should
var y = x.hasOwnProperty;
console.log(y('a')); // Uncaught TypeError: Cannot convert undefined or null to object at hasOwnProperty (<anonymous>)

// example 2:
var x = [1, 2, 3];
console.log(x.includes(4)); // outputs true, as it should
var y = x.includes;
console.log(y('a')); // Uncaught TypeError: Cannot convert undefined or null to object at includes (<anonymous>)

This does not seem like a correct behavior at all, as saving the function in a variable and only then calling it should not make any difference from calling it directly.
So, is this a bug, or a feature?

Yuval.R
  • 1,182
  • 4
  • 15
  • 2
    No, it is not a bug. When you "divorce" a function from an object like that, subsequent invocations will not have the correct `this` value established. – Pointy Aug 02 '22 at 19:52
  • I would classify it as neither bug nor feature, just a consequence of how `this` is handled in JS. – Dave Newton Aug 02 '22 at 19:56
  • Yes, now that I understand the cause, me too. – Yuval.R Aug 02 '22 at 19:56
  • See also [this question](https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work-and-when-should-it-be-used) – Pointy Aug 02 '22 at 19:56

1 Answers1

1

It's a feature.

You'll need

var y = x.hasOwnProperty.bind(x);

to get a version of the method that has its this bound so you can call it as a free function.

AKX
  • 152,115
  • 15
  • 115
  • 172