[removed] Is a member defined?

后端 未结 6 1978
自闭症患者
自闭症患者 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:29

    'bar' in foo 
    

    will look anywhere up the prototype chain. Testing to see if foo.bar !== undefined will also return true if bar is anywhere in foo's prototype chain, but remember if bar is defined on foo, and set to undefined, this will return false.

    hasOwnProperty is more choosy - it will only return true is bar is defined as a direct property of foo.

    Per MDN

    Every object descended from Object inherits the hasOwnProperty method. This method can be used to determine whether an object has the specified property as a direct property of that object; unlike the in operator, this method does not check down the object's prototype chain.

提交回复
热议问题