[removed] Is a member defined?

后端 未结 6 1976
自闭症患者
自闭症患者 2021-02-12 13:38

It seems to me that there are four different ways I can determine whether a given object (e.g. foo) has a given property (e.g. bar) defined:

6条回答
  •  粉色の甜心
    2021-02-12 14:23

    There are indeed some subtle differences between the various methods/keywords.

    1. foo.hasOwnProperty('bar') returns true only if the property 'bar' is defined on the foo object itself. Other properties, such as 'toString' will return false however since they are defined up the prototype chain.

    2. The in keyword operator returns true if the specified property is in the specified object. Both 'bar' in foo and 'toString' in foo would return true.

    3. Since you are checking for the state of the property, the result will be true when bar is not defined on foo and when bar is defined but the value is set to undefined.

提交回复
热议问题