【问题标题】:What is property in hasOwnProperty in JavaScript?JavaScript 中 hasOwnProperty 中的属性是什么?
【发布时间】:2012-03-12 21:15:10
【问题描述】:

考虑:

if (someVar.hasOwnProperty('someProperty') ) {
 // Do something();
} else {
 // Do somethingElse();
}

hasOwnProperty('someProperty') 的正确用法/解释是什么?

为什么我们不能简单地使用someVar.someProperty 来检查对象someVar 是否包含名称为someProperty 的属性?

在这种情况下什么是属性?

这个 JavaScript 检查什么属性?

【问题讨论】:

标签: javascript object hasownproperty


【解决方案1】:

hasOwnProperty 返回一个布尔值,指示您调用它的对象是否具有带有参数名称的属性。例如:

var x = {
    y: 10
};
console.log(x.hasOwnProperty("y")); //true
console.log(x.hasOwnProperty("z")); //false

但是,它不看对象的原型链。

在使用for...in 构造枚举对象的属性时使用它很有用。

如果您想查看完整的详细信息,ES5 specification 一如既往是一个不错的地方。

【讨论】:

  • 原型链的奖励积分。仍在试图弄清楚当它没有调用一个对象时它在调用什么......它不是window
  • @KristofferSHansen - 我也想知道,但问题已经过编辑,所以现在正在一个对象上调用它。如果不是,则会引发错误。
  • 我想这会改变一些事情。在 Chrome 中从控制台运行时没有错误。
  • @KristofferSHansen - 我认为这是因为控制台运行代码的方式(它作为 eval 代码而不是全局或函数代码运行)。我在一个空白的 HTML 页面中尝试了它并得到一个“无法将 null 转换为对象”的错误。
  • @KristofferSHansen 在类方法上调用时查看 Kunal Vashist 的答案
【解决方案2】:

这是一个简短而准确的答案:

在 JavaScript 中,每个对象都有一堆内置的键值对,其中包含有关对象的元信息。当您使用 for...in 构造/循环对象遍历所有键值对时,您也在遍历此元信息键值对(您绝对不想要)。

使用hasOwnPropery(property) filters-out 这些不必要的循环遍历元信息并直接检查参数property 是否是对象中的用户给定属性。 filters-out,我的意思是,hasOwnProperty(property) 不看,property 是否存在于 Object 的原型链也就是元信息中。

它基于此返回布尔值true/false

这是一个例子:

var fruitObject = {"name": "Apple", "shape": "round", "taste": "sweet"};
console.log(fruitObject.hasOwnProperty("name"));  //true
console.log(Object.prototype.hasOwnProperty("toString");) //true because in above snapshot you can see, that there is a function toString in meta-information

我希望它很清楚!

【讨论】:

  • 在你写的例子的最后一行console.log(Object.prototype....;你的意思是console.log(fruitObject.?水果对象还是对象?
  • >"你也在循环遍历这个元信息键值对" 但是当我运行 for (var key in fruitObject) { ... } js 时,无论如何只循环非原型键,我是遗漏了什么还是 JS 运行时改变他们处理 key-in-object 循环的方式?
【解决方案3】:

它检查:

返回一个布尔值,指示对象是否具有指定名称的属性

如果对象具有指定名称的属性,hasOwnProperty 方法返回 true,否则返回 false。此方法不检查该属性是否存在于对象的原型链中;该属性必须是对象本身的成员。

示例:

var s = new String("Sample");
document.write(s.hasOwnProperty("split"));                        //false
document.write(String.prototype.hasOwnProperty("split"));         //true

【讨论】:

  • 我给了一个-1,因为你最初的回答是一个简短且完全不连贯的句子,然后被更新为一个稍长、稍微连贯但完全不准确的句子。
  • @amnotiam- 但我认为它现在已经很清楚了......这是因为我的互联网问题我无法发布更多............
【解决方案4】:

总结:

hasOwnProperty() 是一个可以在任何对象上调用的函数,并将字符串作为输入。如果属性位于对象上,则返回一个布尔值 true,否则返回 false。 hasOwnProperty() 位于 Object.prototype 上,因此可用于任何对象。

示例:

function Person(name) {
  this.name = name;
}

Person.prototype.age = 25;

const willem = new Person('willem');

console.log(willem.name); // Property found on object
console.log(willem.age); // Property found on prototype

console.log(willem.hasOwnProperty('name')); // 'name' is on the object itself
console.log(willem.hasOwnProperty('age')); // 'age' is not on the object itself

在本例中,创建了一个新的 Person 对象。每个 Person 都有自己的名称,该名称在构造函数中被初始化。但是,年龄并不位于对象上,而是位于对象的原型上。因此,hasOwnProperty() 确实返回 true 的姓名和 false 的年龄。

实际应用:

hasOwnProperty() 在使用for in 循环遍历对象时非常有用。如果属性来自对象本身而不是原型,您可以检查它。例如:

function Person(name, city) {
  this.name = name;
  this.city = city;
}

Person.prototype.age = 25;

const willem = new Person('Willem', 'Groningen');

for (let trait in willem) {
  console.log(trait, willem[trait]); // This loops through all properties, including the prototype
}

console.log('\n');

for (let trait in willem) {
  if (willem.hasOwnProperty(trait)) { // This loops only through 'own' properties of the object
    console.log(trait, willem[trait]);
  }
}

【讨论】:

    【解决方案5】:

    您使用 object.hasOwnProperty(p) 来确定对象是否具有 可枚举 属性 p-

    对象可以有自己的原型,其中“默认”方法和属性分配给对象的每个实例。 hasOwnProperty 仅对在构造函数中专门设置或稍后添加到实例的属性返回 true。

    要确定是否在任何地方为对象定义了 p,请使用 if(p instanceof object),其中 p 计算为属性名称字符串。

    例如,默认情况下所有对象都有一个 'toString' 方法,但它不会显示在 hasOwnProperty 中。

    【讨论】:

      【解决方案6】:

      hasOwnProperty 是检查 object 是否具有 property 的正确方法。 someVar.someProperty 不能用作这种情况的替代方案。以下条件将显示出很好的差异:

      const someVar = { isFirst: false };
      
      
      // The condition is true, because 'someVar' has property 'isFirst'
      if (someVar.hasOwnProperty('isFirst')) {
        // Code runs
      }
      
      
      // The condition is false, because 'isFirst' is false.
      if (someVar.isFirst) {
        // Code does not runs here
      }
      

      因此someVar.isFirst 不能用于替代someVar.hasOwnProperty('isFirst')

      【讨论】:

        【解决方案7】:

        hasOwnProperty 是一个接受字符串参数的普通 JavaScript 函数。

        在您的情况下,somevar.hasOwnProperty('someProperty'),它会检查 somevar 函数是否具有 somepropery - 它返回 true 和 false。

        function somevar() {
            this.someProperty = "Generic";
        }
        
        function welcomeMessage()
        {
            var somevar1 = new somevar();
            if(somevar1.hasOwnProperty("name"))
            {
                alert(somevar1.hasOwnProperty("name")); // It will return true
            }
        }
        

        【讨论】:

          【解决方案8】:

          场景A:

          const objA = { a: 1, b: 2 }
          for (const key in objA) {
            if (objA.hasOwnProperty(key)) {
              console.log(objA[key])
            }
          }
          
              Output
          
              1
              2
          
          

          场景 B:

          const objB = {
            a: 1,
            b: 2,
            hasOwnProperty() {
              return false
            }
          }
          
          for (const key in objB) {
            if (objB.hasOwnProperty(key)) {
              console.log(objB[key])
            }
          }
          
              Outputs nothing
          
          

          因为 JavaScript 不保护 hasOwnProperty 的属性。 所以你可以这样使用它:

          for (const key in objB) {
            if (Object.prototype.hasOwnProperty.call(obj, key)) {
              console.log(objB[key])
            }
          }
          

          【讨论】:

            【解决方案9】:

            2021 - Object.hasOwn 替代 Object.hasOwnProperty()

            正如其他答案所示,hasOwnProperty 将检查对象自身的属性,而 in 也会检查继承的属性。

            有一种新的替代方法称为Object.hasOwn(),旨在替代Object.hasOwnProperty()**

            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
            }

            更多关于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

            【讨论】:

              【解决方案10】:

              checks if an object has a property。据我所知,它的工作原理与if(obj.prop) 相同。

              【讨论】:

              • obj.prop 遵循原型链,hasOwnProperty 不遵循
              • 问题是prop 的值是假的。 if(obj.hasOwnProperty('prop')) 将是 trueif(obj.prop) 将是 false
              猜你喜欢
              • 1970-01-01
              • 2017-10-19
              • 2011-04-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-03-17
              • 2021-01-07
              • 2022-08-24
              相关资源
              最近更新 更多