Four different property detection methods in JavaScript comparison

Source: Internet
Author: User
Tags hasownproperty

Tag: span indicates false differentiate BLE method inherit ASC log

Four different property detection methods in JavaScript are compared to 1. Using the In method
var o = {x:1}; inch // true inch // false inch // true, the inherited property can be detected inch // true, non-enumerable properties can be detected

2. hasOwnProperty () method

var o = {x:1};o.hasownproperty (//true//false//  False, cannot detect inherited properties //True, non-enumerable properties can be detected
3. propertyIsEnumerable () method
var o = object.create ({y:2= 1; o.propertyisenumerable (///True,x is an enumerable property // False, inherited property, non-enumerable // false, non-enumerable properties cannot be detected

4.!== undefined method
var o = {x:1///True,o has attribute x//True, inherited property can also be detected

One of the weaknesses of this approach is that there is no way to differentiate between nonexistent attributes and values that are undefined, such as:

var o =//falsein//true

Note that this is "!==" instead of "! =" because "!==" can differentiate between undefined and null.
But sometimes it is not necessary to distinguish between "null" and "undefined", as long as you decide that a property is not null or undefined.

// If o contains an attribute x, and the value of x is not undefined or null,o.x multiplied by 2 if null) o.x *= 2;

An inherited property is not enumerable, so it is possible to detect an inherited property, and it must also detect a non-enumerable property.
X indicates that it cannot be detected, √ indicates that it can detect

Detection Method non-enumerable properties? inherit property?
Inch
hasOwnProperty X
propertyIsEnumerable X X
!==

Four different property detection methods in JavaScript comparison

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.