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);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…