JavaScript detects instance properties, prototype properties _javascript tips

Source: Internet
Author: User
Tags string format

0. Premises

The properties of a JavaScript object are divided into two existing forms. One is the existence of an instance, the other is the existence of a prototype object.

According to the above, there are 4 kinds of cases when detecting properties

There is neither an instance nor a prototype object
There are instances in which there is no prototype object
Does not exist in the instance, exists in the prototype object
In both instances and in the prototype object

1.hasOwnPrototype ()

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

Copy Code code 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 returns true regardless of whether the attribute is present in the instance itself or in a prototype object (2/Condition 3/Condition 4); Otherwise, returns false (condition 1).

Copy Code code as follows:

Console.log (' name ' in Person1); True
Console.log (' name ' in Person2); True

3. Detecting properties of existing prototypes

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

Copy Code code 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 property exists in the prototype and returns True (condition 3). Otherwise return false (condition 1/Condition 2/Condition 4).

The above is the entire content of this article, I hope you can enjoy

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.