Obj.hasownproperty: You can detect whether a property exists in an instance object or in a prototype object, and if it exists in an instance object, return True, as in the example:
The code is as follows |
Copy Code |
function person (argument) { This.name= "Overwrite"; overriding properties in constructors } person.prototype={ Name: "Nike", Sayname:function () { alert (this.name); } } var person1=new person (); Person1.name= in "overwrite";//Instances overriding properties Alert (Person1.hasownproperty ("name")); |
By simply selecting one of the 2 comments in the preceding code to remove the previous comment, alert returns true:
When a property in a prototype object is overridden in an instance or constructor, the hasOwnProperty method returns True, otherwise it returns false.
In operator: Returns true whenever an attribute exists in an instance object or a prototype object.
So, we add a code: Alert ("name" in Person1) that returns true regardless of whether the annotation is removed or not
Native JS does not provide a direct way to determine whether a property exists in a prototype object, but uses the hasOwnProperty () and in operators to implement this function, as follows:
code is as follows |
copy code |
function person (argument) { //this.name= "overwrite";//Constructor overrides property } person.prototype={ Name: "Nike", Sayname:function () { alert (this.name); } } Var person1=new person (), //person1.name= "overwrite";//Instance overriding property Alert (Person1.hasownproperty ("name ")); function Person (argument) { //this.name= "overwrite"; } person.prototype={ Name: "Nike", Sayname:function () { alert (this.name); } } Var person1=new person (), function Hasprototypeproperty (obj,name) { return!obj.hasownproperty (name) && name in obj; } Alert (Hasprototypeproperty (Person1, "name") |
does not remove the annotation code, alert returns the True:name property exists in the prototype object
Remove the annotation code, alert returns the False:name property has been overridden by the instance and cannot directly access the original prototype object property name