0. Premises
The properties of a JavaScript object are divided into two existing forms. One is the existence of an instance, the other is the existence of a prototype object.
According to the above, there are 4 kinds of cases when detecting properties
There is neither an instance nor a prototype object
There are instances in which there is no prototype object
Does not exist in the instance, exists in the prototype object
In both instances and in the prototype object
1.hasOwnPrototype ()
Hasownprototype () accepts a property name in a string format and returns True if the instance itself exists (2/4). Otherwise, returns false (conditions 1/3).
Copy Code code 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 regardless of whether the attribute is present in the instance itself or in a prototype object (2/Condition 3/Condition 4); Otherwise, returns false (condition 1).
Copy Code code as follows:
Console.log (' name ' in Person1); True
Console.log (' name ' in Person2); True
3. Detecting properties of existing prototypes
With the In operator and hasOwnProperty (), you can customize the function to detect whether a given property exists in the prototype.
Copy Code code 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
The given property exists in the prototype and returns True (condition 3). Otherwise return false (condition 1/Condition 2/Condition 4).
The above is the entire content of this article, I hope you can enjoy