【问题标题】:Object.hasOwn() vs Object.prototype.hasOwnProperty()Object.hasOwn() 与 Object.prototype.hasOwnProperty()
【发布时间】:2021-10-13 19:55:32
【问题描述】:

新方法 Object.hasOwn() 返回一个布尔值,指示指定对象是否具有指示的属性作为其自己的属性,但 Object.prototype.hasOwnProperty() 也是如此,它们之间有什么区别以及使用一个比另一个有什么好处?

【问题讨论】:

    标签: javascript javascript-objects prototypal-inheritance hasownproperty hasown


    【解决方案1】:

    使用Object.hasOwn() 代替Object.hasOwnProperty()

    Object.hasOwn() 旨在替代Object.hasOwnProperty(),是一种可供使用的新方法(但尚未得到所有浏览器(如 safari)的完全支持,但很快就会支持)

    Object.hasOwn() 是一个静态方法,如果指定对象具有指定属性作为其自己的属性,则返回 true。如果该属性是继承的,或者不存在,则该方法返回 false。

    const person = { name: 'dan' };
    
    console.log(Object.hasOwn(person, 'name'));// true
    console.log(Object.hasOwn(person, 'age'));// false
    
    const person2 = Object.create({gender: 'male'});
    
    console.log(Object.hasOwn(person2, 'gender'));// false

    建议在Object.hasOwnProperty() 上使用此方法,因为它也适用于使用Object.create(null) 创建的对象以及已覆盖继承的hasOwnProperty() 方法的对象。虽然可以通过在外部对象上调用Object.prototype.hasOwnProperty() 来解决这些问题,但Object.hasOwn() 克服了这些问题,因此是首选(参见下面的示例)

    let person = {
      hasOwnProperty: function() {
        return false;
      },
      age: 35
    };
    
    if (Object.hasOwn(person, 'age')) {
      console.log(person.age); // true - the remplementation of hasOwnProperty() did not affect the Object
    }

    let person = Object.create(null);
    person.age = 35;
    if (Object.hasOwn(person, 'age')) {
      console.log(person.age); // true - works regardless of how the object was created
    }
    
    if (person.hasOwnProperty('age')){ // throws error - person.hasOwnProperty is not a function
       console.log('hasOwnProperty' + person.age);
    }

    更多关于Object.hasOwn的信息可以在这里找到:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn

    浏览器兼容性 - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility

    【讨论】:

    • 不错的答案。只需为想要查看更多详细信息的人(如我)添加指向original proposal 的链接。
    • 为什么“console.log(Object.hasOwn(person2, 'gender'))”返回false?如果您检查 person2.gender,person2 是否拥有该属性?它不是用麻烦的“Object.create(null)”创建的,所以很好奇为什么它不返回 true。
    • 因为 Gender 不是在 person2 对象上创建的,而是在它的原型上创建的。
    猜你喜欢
    • 2016-08-31
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    相关资源
    最近更新 更多