Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access the Object.prototype method in the following logic?

People also ask

How do you access object prototype?

The constructor property points back to the function on which prototype object is a property. We can access the function's prototype property using functionName. prototype .

How do you create an object with prototype?

Another method to create an object is by defining its prototype. 2. Prototypes: Every JavaScript function has a prototype object property that is empty by default. We can initialize methods and properties to this prototype for creating an object.

What is function __ proto __?

__proto__ is a non standard accessor to the prototype, which is supported across browsers, but not by IE. Anyway is not meant to be used by application code. Follow this answer to receive notifications.

What is object prototype hasOwnProperty?

prototype. hasOwnProperty() The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).


You can access it via Object.prototype:

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

That should be safer, because

  • Not all objects inherit from Object.prototype
  • Even for objects which inherit from Object.prototype, the hasOwnProperty method could be shadowed by something else.

Of course, the code above assumes that

  • The global Object has not been shadowed or redefined
  • The native Object.prototype.hasOwnProperty has not been redefined
  • No call own property has been added to Object.prototype.hasOwnProperty
  • The native Function.prototype.call has not been redefined

If any of these does not hold, attempting to code in a safer way, you could have broken your code!

Another approach which does not need call would be

!!Object.getOwnPropertyDescriptor(obj, prop);

For your specific case, the following examples shall work:

if(Object.prototype.hasOwnProperty.call(entries, "key")) {
    //rest of the code
}

OR

if(Object.prototype.isPrototypeOf.call(entries, key)) {
    //rest of the code
}

OR

if({}.propertyIsEnumerable.call(entries, "key")) {
    //rest of the code
}

It seems like this would also work:

key in entries

since that will return a boolean on whether or not the key exists inside the object?