0. Prerequisite
The properties of JavaScript objects are divided into two forms of existence. One is the existence instance and the other is the existence in the prototype object.
According to the above, there will be 4 situations when detecting attributes
Neither in instances nor in prototype objects
In the instance, it does not exist in the prototype object
In the instance, it exists in the prototype object
exists in both instances and in prototype objects
1.hasOwnPrototype()
hasOwnPrototype() accepts a property name in string format, and returns true if the instance itself has this property (case 2/case 4). Otherwise, it returns false (case 1/case 3).
The code copy 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 will return true regardless of whether the attribute exists in the instance itself or in the prototype object (case 2/case 3/case 4); otherwise, it will return false (case 1).
The code copy is as follows:
console.log('name' in person1); //true
console.log('name' in person2); //true
3. Detect the properties of the prototype
Combining the in operator and hasOwnProperty() can customize the function to detect whether the given attribute exists in the prototype.
The code copy 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
The given attribute exists in the prototype, returns true (case 3). Otherwise, false (case 1/case 2/case 4).
The above is the entire content of this article. I hope you like it