Friends who need tips on using JavaScript isPrototypeOf and hasOwnProperty can refer to it.
1. isPrototypeOf
isPrototypeOf is used to determine whether the specified object object1 exists in the prototype chain of another object object2. If so, it returns true, otherwise it returns false.
The format is as follows:
object1.isPrototypeOf(object2);
object1 is an instance of an object;
object2 is another object whose prototype chain will be checked.
The prototype chain can be used to share functionality between different instances of the same object type.
If the prototype chain of object2 contains object1, then the isPrototypeOf method returns true.
If object2 is not an object or object1 does not appear in the prototype chain in object2, the isPrototypeOf method will return false.
Usage examples are as follows:
var re = /^\s*/;
// Define a regular expression object here
// Check whether RegExp is the prototype chain object of re , returns true
var bIsptt = RegExp.prototype.isPrototypeOf(re);
2. hasOwnProperty hasOwnProperty determines whether an object has a named attribute or object. This method cannot check the Whether the object has this property in its prototype chain, the property must be a member of the object itself.
If the property or method is defined by the object itself rather than in the prototype chain, return true; otherwise, return false;
The format is as follows:
object.hasOwnProperty(proName);
Judgement The name of proName is not a property or object of the object object. Usage examples are as follows:
// Get false because the properties in the prototype chain cannot be detected
var bStr = "Test String".hasOwnProperty("split");
// The prototype of the String object This property already exists, so it naturally returns true
var bStr1 = String.prototype.hasOwnProperty("split");
// Returns true because it is not detecting the property in the prototype
var bObj = ({ fnTest:function(){}}).hasOwnProperty("fnTest");
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Focus on explaining the __proto__ attribute in JavaScript (pictures and texts) Tutorial)
The above is the detailed content of Differences in usage of JavaScript isPrototypeOf and hasOwnProperty (practical). For more information, please follow other related articles on the PHP Chinese website!