Whether the JS object has a certain attribute
Two methods, 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 whether it is name or toString on the prototype chain, it can be detected and returned true.
2. hasOwnProperty method
var obj = {name:'jack'}; obj.hasOwnProperty('name'); // --> true obj.hasOwnProperty('toString'); // --> false
The properties inherited from the prototype chain cannot be detected by hasOwnProperty and return false.
It should be noted that although in can detect the properties of the prototype chain, for in usually cannot.
Of course, after rewriting the prototype, for in will be visible under IE9/Firefox/Safari/Chrome/Opera. See: Defects of for in
Thank you for reading, I hope it can help everyone, thank you for your support of this site!
For more related articles on how to determine whether a JS object has a certain attribute, please pay attention to the PHP Chinese website!