Is it safe to use methods from Object.prototype on any object directly?

Shubham Akodiya
GAMMASTACK
Published in
3 min readJun 27, 2019

How we learn is far more important than what we learn — Anonymous

If you were to accidentally open any JS library (accidentally here because we hardly get the time to view any JS library code 😄 we are usually busy to complete the task with the help of our dear workmate ‘StackOverflow’), you would probably see something like this:

// Check whether path exits as a property of givenObject or not
function has(givenObject, path) {
return givenObject != null && hasOwnProperty.call(givenObject, path);
}

The above ‘has’ method code is taken from the famous lodash library:

On closely observing the above function, you may ask the following questions to yourself:

  • givenObject is already an object, so why was the code not written like givenObject .hasOwnProperty? (As it is a prototype method available on all the objects)
  • Why the hasOwnProperty method from the Object was used to validate the property like this Object.prototype.hasOwnProperty.call(givenObject, path)?

It sounds very confusing because we usually use the approach of calling the prototype method directly in our code, so why they wrote like this?

So now, It’s time to give yourself a 5-minute break and think about why?

Time finished !! Were you able to figure out why it was done in that manner? So before going to the answer, I think, we should look at the different ways of creating an object in JavaScript:

// the most commonly used
var obj1 = {};
// seldom used
var obj2 = new Object();
// Required to pass an object
var obj3 = Object.create({});
var obj4 = Object.create(null);

Wait !! There comes another question.

What’s the difference between obj4 and other objects obj3, obj2, obj1?

Let’s check in console:

Did you find something interesting in this image?

Obj4 has no prototype methods. We can’t use obj4.hasOwnProperty or any prototype methods. Now I think, you got the answer about why library developers do not directly call the obj.hasOwnProperty or any prototype methods.

Now, if we take the above lodash ‘has’ method case, there would be some errors, if library developer directly calls the hasOwnProperty method on the given object -

  • If givenObject was created using the same way as obj4 then there would be no chance of calling method hasOwnProperty.
  • As per the 1st point, there would be some errors and it makes a false impression to the library users and this may lead to there hard work in vain only because of a silly mistake.

What we learned -

  • The power of the call method.
  • How to call any prototype method without using the given object prototype.
  • Why the library writes the code like this way?
  • Better code style.

Thanks for reading this article and your time :)

--

--