SoFunction
Updated on 2025-02-28

JavaScript isPrototypeOf and hasOwnProperty use difference

1、isPrototypeOf
isPrototypeOf is used to determine whether the specified object object1 exists in the prototype chain of another object object2. If it is, it returns true, otherwise it returns false.
The format is as follows:
(object2);
object1 is an instance of an object;
object2 is another object that will check its prototype chain.
Prototype chains can be used to share functionality among different instances of the same object type.
If object1 is included in the prototype chain of object2, 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.
Examples of use are as follows:
Copy the codeThe code is as follows:

var re = /^\s*/;
// Here is a regular expression object
// Check here whether RegExp is the original chain object of re, and returns true
var bIsptt = (re);

2、hasOwnProperty
hasOwnProperty determines whether an object has a name attribute or object. This method cannot check whether the object's prototype chain has this attribute. This attribute must be a member of the object itself.
Return true if the property or method is defined by the object itself rather than defined in the prototype chain of the device; otherwise return false;
The format is as follows:
(proName);
Determine whether the name of the proName is an attribute or object of the object object. Examples of use are as follows:
Copy the codeThe code is as follows:

// Get false because the properties in the prototype chain cannot be detected
var bStr = "Test String".hasOwnProperty("split");
// This property is already on the prototype of the String object, so it will naturally return true.
var bStr1 = ("split");
// Return true because it is not a property in the prototype to detect
var bObj = ({fnTest:function(){}}).hasOwnProperty("fnTest");