How to Determine Whether an JS Object Has an Attribute
- 2021-07-16 01:17:16
- OfStack
Whether the JS object has a property
Two ways, but slightly different
1. in operator
var obj = {name:'jack'};
alert('name' in obj); // --> true
alert('toString' in obj); // --> true
It can be seen that both name and toString on the prototype chain can detect the return true.
2. hasOwnProperty method
var obj = {name:'jack'};
obj.hasOwnProperty('name'); // --> true
obj.hasOwnProperty('toString'); // --> false
Attributes inherited from the prototype chain cannot be detected by hasOwnProperty, returning false.
Note that although in can detect the properties of the prototype chain, for in usually does not.
Of course, for in is visible under IE9/Firefox/Safari/Chrome/Opera after rewriting the prototype. See: Defects in for in
Thank you for reading, hope to help everyone, thank you for your support to this site!