Two ways to judge whether a JS object has a certain attribute _javascript skill

Source: Internet
Author: User

Two ways, but slightly different

1,in operator

Copy Code code as follows:

var obj = {name: ' Jack '};
Alert (' name ' in obj); --> true
Alert (' toString ' in obj); --> true

You can see that the return true is detected either by name or by ToString on the prototype chain.

2,hasownproperty method

Copy Code code as follows:

var obj = {name: ' Jack '};
Obj.hasownproperty (' name '); --> true
Obj.hasownproperty (' toString '); --> false

The inherited attribute on the prototype chain could not be detected by hasOwnProperty and returns false.

It should be noted that although in can detect the properties of the prototype chain, for-in is usually not.

Of course, after the prototype is rewritten, for-in is visible under Ie9/firefox/safari/chrome/opera. See: For the flaw in

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.