Home  >  Article  >  Web Front-end  >  JavaScript detects instance attributes and prototype attributes_javascript tips

JavaScript detects instance attributes and prototype attributes_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:16:021067browse

0. Prerequisite

The properties of JavaScript objects are divided into two forms of existence. One is in the instance, and the other is in the prototype object.

According to the above, 4 situations will occur when detecting attributes

Does not exist in the instance or prototype object
Exists in the instance, does not exist in the prototype object
Does not exist in the instance, exists in the prototype object
It exists both in the instance and in the prototype object

1.hasOwnPrototype()

hasOwnPrototype() accepts a property name in string format, and if the property exists in the instance itself (case 2/case 4), returns true. Otherwise, returns false (case 1/case 3).

Copy code The code 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 (case 2/case 3/case 4) regardless of whether the attribute exists in the instance itself or the prototype object; otherwise, it will return false (case 1).

Copy code The code is as follows:

console.log('name' in person1); //true
console.log('name' in person2); //true

3. Detect the existence of prototype attributes

Combined with the in operator and hasOwnProperty(), you can customize a function to detect whether a given property exists in the prototype.

Copy code The code 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

If the given attribute exists in the prototype, return true (case 3). Otherwise, return false (case 1/case 2/case 4).

The above is the entire content of this article, I hope you all like it

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn