7

Code one:

obj.hasOwnProperty(prop);

Code Two:

const hasOwnProperty = Object.prototype;
hasOwnProperty.call(obj, prop); 

I always use the first coding style, but I saw several times about the second coding style in some JS books or github projects. I want to know it's just a habit or really a better way to write my js code. Thanks.

whoami - fakeFaceTrueSoul
  • 17,086
  • 6
  • 32
  • 46
ShanshanXu
  • 81
  • 3
  • 1
    you are supposed to use the function variable for example when you need to select the function based on some condition – mangusta Jun 04 '20 at 03:39
  • From ur question :: *but I saw several times about the second coding style in some JS books or github projects* ---> Yes if you use ESLint then it would throw an error on `obj.hasOwnProperty()`, So you need to use the other one may be that's one reason dev's might be opting the 2nd approach, Yes the reason why it errors out is explained by accepted answer or here :: https://stackoverflow.com/q/39282873/7237613 – whoami - fakeFaceTrueSoul Jun 04 '20 at 16:22

1 Answers1

5

If the obj is not tampered with, there is relatively little difference. But all sorts of stuff can get in the way if you rely on obj containing the prototype function as you expect it to work (potentially even by accident). This is why you'll often see libraries make calls to the prototype methods directly instead of relying on them being in tact on the individual objects.

Consider this case:

const prop = 'test';

obj = {test: 'example'};
console.log({
 'version': 'no tampering!',
 'obj.hasOwnProperty': obj.hasOwnProperty(prop),
 'Object.prototype.hasOwnProperty': Object.prototype.hasOwnProperty.call(obj, prop)
});

// someone does something you don't expect with obj
obj.hasOwnProperty = () => false;
// NOTE: This at least is a function, there is nothing to stop me from setting it to something that would BREAK the function call...
// E.g. obj.hasOwnProperty = 42;

console.log({
 'version': 'some tampering!',
 'obj.hasOwnProperty': obj.hasOwnProperty(prop),
 'Object.prototype.hasOwnProperty': Object.prototype.hasOwnProperty.call(obj, prop)
});

Or, what if obj is an object that does not inherit the Object prototype?

const obj =  Object.create(null);

console.log(obj.hasOwnProperty);
Chase
  • 3,028
  • 14
  • 15
  • Thanks. I thought that style would do help to avoid some judgement of type, but I've never considered that someone would try to change the property ``` hasOwnProperty``` or even inhiret from null.. got it – ShanshanXu Jun 04 '20 at 06:24