Home > Article > Web Front-end > JavaScript detects instance attributes and prototype attributes_javascript tips
0. Prerequisite
The properties of JavaScript objects are divided into two forms of existence. One is in the instance, and the other is in the prototype object.
According to the above, 4 situations will occur when detecting attributes
Does not exist in the instance or prototype object
Exists in the instance, does not exist in the prototype object
Does not exist in the instance, exists in the prototype object
It exists both in the instance and in the prototype object
1.hasOwnPrototype()
hasOwnPrototype() accepts a property name in string format, and if the property exists in the instance itself (case 2/case 4), returns true. Otherwise, returns false (case 1/case 3).
2.in operator
Thein operator will return true (case 2/case 3/case 4) regardless of whether the attribute exists in the instance itself or the prototype object; otherwise, it will return false (case 1).
3. Detect the existence of prototype attributes
Combined with the in operator and hasOwnProperty(), you can customize a function to detect whether a given property exists in the prototype.
If the given attribute exists in the prototype, return true (case 3). Otherwise, return false (case 1/case 2/case 4).
The above is the entire content of this article, I hope you all like it