Benefit of using Object.hasOwnProperty vs. testing if a property is undefined

后端 未结 3 1949
心在旅途
心在旅途 2021-02-05 11:02

Since hasOwnProperty has some caveats and quirks (window / extensive use in Internet Explorer 8 issues, etc.):

Is there any reason to even use it

3条回答
  •  -上瘾入骨i
    2021-02-05 11:18

    The hasOwnProperty method checks that a property is assigned to the object directly.

    So, if property 'a' is in the prototype, hasOwnProperty will filter that.

    function NewClass() {}
    NewClass.prototype = { a: 'there' };
    var obj = new NewClass();
    
    if (obj.hasOwnProperty('a')) { /* Code does not work */ }
    if (obj.a !== undefined) { /* Code works */ }
    

    So, hasOwnProperty is safer in many cases.

提交回复
热议问题