Two methods to determine whether a JS object has certain attributes _ javascript tips-js tutorial

Source: Internet
Author: User
This article mainly introduces two methods to determine whether a JS object has a certain attribute. If you need it, you can refer to the two methods, but there are some differences.

1, in Operator

The Code is as follows:


Var obj = {name: 'jack '};
Alert ('name' in obj); // --> true
Alert ('tostring' in obj); // --> true

We can see that both the name and the toString on the prototype chain can detect that the return value is true.

2. hasOwnProperty Method

The Code is as follows:


Var obj = {name: 'jack '};
Obj. hasOwnProperty ('name'); // --> true
Obj. hasOwnProperty ('tostring'); // --> false

Attributes inherited from the prototype chain cannot be detected through hasOwnProperty. false is returned.

It should be noted that, although in can detect the attributes of the prototype chain, for in usually does not work.

Of course, after the prototype is rewritten, for in is visible under IE9/Firefox/Safari/Chrome/Opera. See: for in defects

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.