This article mainly introduces the JavaScript detection of instance attributes and prototype attributes. For more information about the attributes, see <g id = "1"> prerequisite </g>.
The property of a JavaScript object can be divided into two types: exist in an instance and exist in a prototype object.
According to the above, four situations may occur during attribute detection.
Neither instance nor prototype object
Exist in instance, not in prototype object
The instance does not exist and the prototype object exists.
Both instances and prototype objects exist.
1. hasOwnPrototype ()
HasOwnPrototype () accepts an attribute name in string format. if the instance itself has this attribute (case 2/case 4), true is returned. otherwise, false is returned (case 1/case 3 ).
The code is as follows:
Functino Person (){}
Person. prototype. name = 'apple ';
Var person1 = new Person ();
Var person2 = new Person ();
Person1.name = 'banana ';
Console. log (person1.hasOwnPrototype (name); // true
Console. log (person2.hasOwnPrototype (name); // false
2. in operator
The in operator returns true (case 2/case 3/case 4) regardless of whether the attribute exists in the instance or the prototype object. otherwise, false (case 1) is returned ).
The code is as follows:
Console. log ('name' in person1); // true
Console. log ('name' in person2); // true
3. check the prototype attributes.
Combined with the in operator and hasOwnProperty (), you can define a function to check whether a given attribute exists in the prototype.
The code is as follows:
Function hasPrototypeProperty (object, name ){
Return! Object. hasOwnPrototype (name) & (name in object );
}
Console. log (hasPrototypeProperty (person1, 'name'); // false
Console. log (hasPrototypeProperty (person2, 'name'); // true
If a given attribute exists in the prototype, true is returned (case 3). otherwise, false is returned (case 1/case 2/case 4 ).
The above is all the content of this article. I hope you will like it.