Home > Mobile >  JavaScript function saved in variable causes error, bug, or feature?
JavaScript function saved in variable causes error, bug, or feature?

Time:08-03

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?

CodePudding user response:

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.

  • Related