Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do references to Function.prototype functions not work

Tags:

javascript

Why does the second case not working?

// 1. works
Object.prototype.hasOwnProperty.call({a:1}, 'a');

// 2. does not work
var hasProp = Object.prototype.hasOwnProperty.call;
hasProp({a:1}, 'a');

http://jsbin.com/ramenaxame/2/edit?js,console

like image 830
Anri Avatar asked Aug 07 '26 16:08

Anri


1 Answers

Note that all functions share the same call method, inherited from Function.prototype.

Object.prototype.hasOwnProperty.call === Function.prototype.call // true

When you call call on a function, that function becomes the this value for call, so call can call the function. This is the case of your first code, which works.

However, in your second code, you don't call call as a method of an object. Therefore, its this value will be undefined in strict mode, or the global object in non-strict mode. Neither undefined nor the global object are callable, so call will throw.

In fact, your code is equivalent to

var hasProp = Function.prototype.call;
hasProp({a:1}, 'a');

As you can see, there is no reference to hasOwnProperty, so it can't work.

You can fix that using call to call call with hasOwnProperty as the this value:

var call = Function.prototype.call;
call.call(Object.prototype.hasOwnProperty, {a:1}, 'a');

But a better idea would be creating a new function that behaves like call but has its this value bound to hasOwnProperty. You can use bind to achieve this:

var hasProp = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
hasProp({a:1}, 'a');
like image 195
Oriol Avatar answered Aug 10 '26 05:08

Oriol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!