Why is hasOwnProperty being invoked generically here?

后端 未结 3 1492
不思量自难忘°
不思量自难忘° 2021-01-06 04:20

The following function is mentioned in Speaking Javascript: An In-Depth Guide for Programmers by Axel Rauschmayer:

function getDefiningObject(obj, p         


        
3条回答
  •  -上瘾入骨i
    2021-01-06 04:38

    Because obj.hasOwnProperty would terribly fall if the object was defined like these:

    var obj = { hasOwnProperty: 123 };
    
    var obj = Object.create(null);
    

    With {}.hasOwnProperty you get a reference to the desired function from Object.prototype, you don't need to worry about it being shadowed somewhere closer in the prototypical chain, or the object not inheriting from Object.prototype.

    This is a design problem, because hasOwnProperty should have been a static method, but now it's too late to fix it. Another solution is implementing HasOwnProperty manually:

    Object.getOwnPropertyDescriptor(obj, prop) !== undefined
    

提交回复
热议问题