简体   繁体   English

JavaScript中的hasOwnProperty是什么属性?

[英]What is property in hasOwnProperty in JavaScript?

Consider:考虑:

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

What is the right use/explanation of hasOwnProperty('someProperty') ? hasOwnProperty('someProperty')的正确使用/解释是什么?

Why can't we simply use someVar.someProperty to check if an object someVar contains property with name someProperty ?为什么我们不能简单地使用someVar.someProperty来检查 object someVar包含名称为someProperty的属性?

What is a property in this case?在这种情况下,财产是什么?

What property does this JavaScript check?这个 JavaScript 检查什么属性?

hasOwnProperty returns a boolean value indicating whether the object on which you are calling it has a property with the name of the argument. hasOwnProperty返回一个布尔值,指示您调用它的对象是否具有带有参数名称的属性。 For example:例如:

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

However, it does not look at the prototype chain of the object.但是,它不查看对象的原型链。

It's useful to use it when you enumerate the properties of an object with the for...in construct.当您使用for...in构造枚举对象的属性时,使用它很有用。

If you want to see the full details, the ES5 specification is, as always, a good place to look.如果您想查看完整的详细信息, ES5 规范一如既往是一个不错的地方。

Here is a short and precise answer:这是一个简短而准确的答案:

In JavaScript, every object has a bunch of built-in key-value pairs that have meta information about the object.在 JavaScript 中,每个对象都有一堆内置的键值对,其中包含有关对象的元信息。 When you loop through all the key-value pairs using for...in construct/loop for an object you're looping through this meta-information key-value pairs too (which you definitely don't want).当您使用for...in构造/循环遍历对象的所有键值对时for...in您也在遍历此元信息键值对(您绝对不想要)。

在此处输入图片说明

Using hasOwnPropery(property) filters-out these unnecessary looping through meta information and directly checks that is the parameter property is a user-given property in the object or not.使用hasOwnPropery(property)过滤掉这些不必要的元信息循环,并直接检查参数property是否是对象中的用户给定属性。 By filters-out , I mean, that hasOwnProperty(property) does not look if, property exists in Object's prototype chain aka meta information.我的意思是,通过过滤器hasOwnProperty(property)不会查看对象的原型链(即元信息hasOwnProperty(property)中是否存在property

It returns boolean true/false based on that.它基于此返回布尔值true/false

Here is an example:下面是一个例子:

 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

I hope it's clear!我希望很清楚!

It checks:它检查:

Returns a Boolean value indicating whether an object has a property with the specified name返回一个布尔值,指示对象是否具有指定名称的属性

The hasOwnProperty method returns true if the object has a property of the specified name, false if it does not.如果对象具有指定名称的属性,则hasOwnProperty方法返回 true,否则返回 false。 This method does not check if the property exists in the object's prototype chain;该方法不检查该属性是否存在于对象的原型链中; the property must be a member of the object itself.该属性必须是对象本身的成员。

Example:例子:

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

Summary:概括:

hasOwnProperty() is a function which can be called on any object and takes a string as an input. hasOwnProperty()是一个可以在任何对象上调用的函数,它接受一个字符串作为输入。 It returns a boolean which is true if the property is located on the object, otherwise it returns false.它返回一个布尔值,这是true ,如果物业所在的对象,否则返回false。 hasOwnProperty() is located on Object.prototype and thus available for any object. hasOwnProperty()位于Object.prototype ,因此可用于任何对象。

Example:例子:

 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

In this example a new Person object is created.在本例中,创建了一个新的 Person 对象。 Each Person has its own name which gets initialized in the constructor.每个 Person 都有自己的名字,它在构造函数中被初始化。 However, the age is not located on the object but on the prototype of the object.但是,年龄并不位于物体上,而是位于物体的原型上。 Therefore hasOwnProperty() does return true for name and false for age.因此hasOwnProperty()确实为 name 返回true ,为 age 返回false

Practical applications:实际应用:

hasOwnProperty() can be very useful when looping over an object using a for in loop. hasOwnProperty()在使用for in循环遍历对象时非常有用。 You can check with it if the properties are from the object itself and not the prototype.您可以使用它检查属性是否来自对象本身而不是原型。 For example:例如:

 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]); } }

You use object.hasOwnProperty( p ) to determine if an object has an enumerable property p -您使用 object.hasOwnProperty( p ) 来确定对象是否具有可枚举属性p -

An object can have its own prototype, where 'default' methods and attributes are assigned to every instance of the object.对象可以有自己的原型,其中“默认”方法和属性被分配给对象的每个实例。 hasOwnProperty returns true only for the properties that were specifically set in the constructor, or added to the instance later. hasOwnProperty 仅针对在构造函数中专门设置或稍后添加到实例中的属性返回 true。

To determine if p is defined at all, anywhere, for the object, use if( p instanceof object), where p evaluates to a property-name string.要确定是否在任何地方为对象定义了p ,请使用 if( p instanceof object),其中 p 的计算结果为属性名称字符串。

For example, by default all objects have a 'toString' method, but it will not show up in hasOwnProperty.例如,默认情况下所有对象都有一个 'toString' 方法,但它不会出现在 hasOwnProperty 中。

hasOwnProperty is a proper way of checking an object has a property or not. hasOwnProperty是检查对象是否具有属性的正确方法。 someVar.someProperty cannot be used as an alternative to this situation. someVar.someProperty不能用作这种情况的替代方案。 The following condition will show a good difference:以下条件将显示出很好的差异:

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
}

Hence someVar.isFirst cannot be used alternative to someVar.hasOwnProperty('isFirst') .因此someVar.isFirst不能用于替代someVar.hasOwnProperty('isFirst')

hasOwnProperty is a normal JavaScript function that takes a string argument. hasOwnProperty 是一个普通的 JavaScript 函数,它接受一个字符串参数。

In your case, somevar.hasOwnProperty('someProperty') , it checks the somevar function has somepropery or not - it returns true and false.在你的情况, somevar.hasOwnProperty('someProperty')它会检查somevar函数somepropery或不-它返回真假。

Say

function somevar() {
    this.someProperty = "Generic";
}

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

What is the right use/explanation of hasOwnProperty('someProperty')? hasOwnProperty('someProperty') 的正确用法/解释是什么?

The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it). hasOwnProperty()方法返回一个boolean ,指示 object 是否将指定的属性作为其自身属性(而不是继承它)。

 const someVar = {}; someVar.someProperty = 'Foo'; console.log(someVar.hasOwnProperty('someProperty')); // expected output: true console.log(someVar.hasOwnProperty('someProperty1')); // expected output: false

Why can't we simply use someVar.someProperty to check if an object someVar contains property with name someProperty?为什么我们不能简单地使用 someVar.someProperty 来检查 object someVar 是否包含名称为 someProperty 的属性?

someVar.someProperty will return the property value, You can not check that this property is available in the object or not via someVar.someProperty . someVar.someProperty将返回属性值,您无法通过someVar.someProperty检查此属性在 object 中是否可用。

Now in ES2022, A new method has been introduced which is Object.hasOwn(<object reference>, <property name>) this method is intended as a replacement for Object.hasOwnProperty() which overcome some limitations of .hasOwnProperty() .现在在 ES2022 中,引入了一个新方法Object.hasOwn(<object reference>, <property name>)此方法旨在替代Object.hasOwnProperty() ,它克服了.hasOwnProperty()的一些限制。

Scene A:场景一:

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

    Output

    1
    2

Scene B:场景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

Because JavaScript doesn't protect the property of hasOwnProperty.因为 JavaScript 不保护 hasOwnProperty 的属性。 So you can use it like this:所以你可以像这样使用它:

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

2021 - Object.hasOwn as a replacement for Object.hasOwnProperty() 2021 - Object.hasOwn 作为 Object.hasOwnProperty() 的替代品

As other answers indicated, hasOwnProperty will check for an object own properties in contrast to in which will also check for inherited properties.正如其他答案所示, hasOwnProperty将检查对象自己的属性,而in还将检查继承的属性。

There is a new alternative method called Object.hasOwn() and is intended to be a replacement for Object.hasOwnProperty() **有一个名为Object.hasOwn()的新替代方法,旨在替代Object.hasOwnProperty() **

Object.hasOwn() is a static method which returns true if the specified object has the specified property as its own property. Object.hasOwn()是一个静态方法,如果指定的对象具有指定的属性作为它自己的属性,则返回 true。 If the property is inherited, or does not exist, the method returns false.如果该属性被继承或不存在,则该方法返回 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

It is recommended to this method use over the Object.hasOwnProperty() because it also works for objects created by using Object.create(null) and for objects that have overridden the inherited hasOwnProperty() method.建议将此方法用于Object.hasOwnProperty()因为它也适用于使用Object.create(null)创建的对象以及覆盖继承的hasOwnProperty()方法的对象。 Although it's possible to solve these kind of problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() overcome these problems, hence is preferred (see examples below)尽管可以通过在外部对象上调用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 }

More about Object.hasOwn can be found here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn更多关于Object.hasOwn可以在这里找到: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn

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

It checks if an object has a property .检查对象是否具有属性 It works the same as if(obj.prop) , as far as I know.据我所知,它的工作原理与if(obj.prop)相同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM