[removed] Is a member defined?

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

    No they are totally different. Example:

    foo = {bar: undefined};
    Object.prototype.baz = undefined;
    Object.prototype.bing = "hello";
    

    Then:

    (typeof foo.bar != "undefined")  === false
    ('bar' in foo)                   === true
    (foo.hasOwnProperty('bar'))      === true
    
    
    (typeof foo.baz != "undefined")  === false
    ('baz' in foo)                   === true
    (foo.hasOwnProperty('baz'))      === false
    
    
    (typeof foo.bing != "undefined") === true
    ('bing' in foo)                  === true
    (foo.hasOwnProperty('bing'))     === false
    

    Logic-wise:

    • foo.hasOwnProperty('bar') implies 'bar' in foo
    • typeof foo.bar != "undefined" implies 'bar' in foo
    • But those are the only inferences you can draw; no other implications are universally true, as the above counterexamples show.

提交回复
热议问题