0

How does this function determine if a property exists on the prototype?

function hasPrototypeProperty(object, name){
    return !object.hasOwnProperty(name) && (name in object);
}

I am confused by two things:

What is the ! operator doing to the hasOwnProperty method?

And while && seems to saying (name in object) has to be true as well, I am kind of not sure...

I know hasOwnProperty will only return true if the property exists on a instance, but I read it still checks the prototype, if so, what for? That seems like a strange thing to do if the instance is the only thing which matters?

Thanks in advance!

Antonio Pavicevac-Ortiz
  • 7,239
  • 17
  • 68
  • 141

2 Answers2

1

Basically it's checking exclusively if an enumerable property is inherited.

To do this it checks the hasOwnProperty() method to see if the property in the object doesn't (! not operator) directly belong to object:

that are not set in hasOwnProperty !object.hasOwnProperty(name).


And if the in operator returns true it means it belongs to the object's prototype chain

even if it's not a direct property it can be called on object since they belong to the inheritance


But remember name in object returns true only if the property is enumerable;
for ex.: toString() won't ( because it's a nonenumerable property).

maioman
  • 18,154
  • 4
  • 36
  • 42
1

What is the ! operator doing to the hasOwnProperty method?

It's the boolean NOT operator. It doesn't do anything to the method, but to the result of the call.

And while && seems to saying (name in object) has to be true as well, I am kind of not sure...

Yes, that's what it does.

I know hasOwnProperty will only return true if the property exists on a instance, but I read it still checks the prototype, if so, what for?

Not, it does not check the prototype. The in operator does however.

So basically that hasPrototypeProperty function will return true iff the object has no own property with the given name, but there is a possible inherited property with that name on the object.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375