Reputation: 18666
I'm maintaining a javascript library whose original author is not longer working at the company.
I've found the following pattern repeated across the library:
var events = {}; // defined globally
// many lines below within a function:
if(!events.hasOwnProperty.call(events, eventKey)) return;
Does the use of call
in that way offer any technical advantage over just doing:
if (!events.hasOwnProperty(eventKey)) return;
I feel like the former is less intuitive than the latter, and the latter is more expressive assuming the output is identical
Upvotes: 0
Views: 45
Reputation: 16515
Both are the same! There is no diffrerence. Any Object {}
has the method hasOwnProperty()
(Object.prototype.hasOwnProperty
), what is a function (or function object) and any function (-object) has a method call()
(Function.prototype.call
) mdn-docs
And the first argument of Function.prototype.call()
is the »this context/object«, or context/sidecar/this/that/etc…
So, in your case: events.hasOwnProperty.call(events, …)
is just the very same as events.hasOwnProperty(…)
, since in the first case events
will be this
, because it was used as first argument to call()
. In the latter case, events
will also be this
, since JS will always set the context/this automatically on each objects' method, if you do obj.method()
.
Or in code:
var
A = { log: console.log(this) },
B = {};
A.log() // A
A.log.call(A) // A
A.log.call(B) // B
Upvotes: 1