admin管理员组文章数量:1134030
Consider:
if (someVar.hasOwnProperty('someProperty') ) {
// Do something();
} else {
// Do somethingElse();
}
What is the right use/explanation of hasOwnProperty('someProperty')
?
Why can't we simply use someVar.someProperty
to check if an object someVar
contains property with name someProperty
?
What is a property in this case?
What property does this JavaScript check?
Consider:
if (someVar.hasOwnProperty('someProperty') ) {
// Do something();
} else {
// Do somethingElse();
}
What is the right use/explanation of hasOwnProperty('someProperty')
?
Why can't we simply use someVar.someProperty
to check if an object someVar
contains property with name someProperty
?
What is a property in this case?
What property does this JavaScript check?
Share Improve this question edited May 31, 2024 at 6:59 dumbass 27.2k4 gold badges36 silver badges73 bronze badges asked Feb 22, 2012 at 14:19 FLYFLY 2,4595 gold badges30 silver badges40 bronze badges 3- 4 stackoverflow.com/questions/2600085/… – Dor Cohen Commented Feb 22, 2012 at 14:23
- When I asked this question I thought it was a function that checked some html. Now I see it checking a javascript object or method for a 'variable' within that object or method. thnx! – FLY Commented Feb 22, 2012 at 14:39
- Have a look at developer.mozilla.org/en/JavaScript/Reference/Global_Objects/… – Felix Kling Commented Feb 22, 2012 at 14:52
13 Answers
Reset to default 208hasOwnProperty
returns a boolean value indicating whether the object on which you are calling it has a property with the name of the argument. 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.
If you want to see the full details, the ES5 specification is, as always, a good place to look.
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. 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).
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.
By filters-out, I mean, that hasOwnProperty(property)
does not look if, property
exists in Object's prototype chain aka meta information.
It returns boolean true/false
based on that.
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!
Summary:
hasOwnProperty()
is a function which can be called on any object and takes a string as an input. It returns a boolean which is true
if the property is located on the object, otherwise it returns false. hasOwnProperty()
is located on Object.prototype
and thus available for any object.
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. Each Person has its own name which gets initialized in the constructor. 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.
Practical applications:
hasOwnProperty()
can be very useful when looping over an object using a for in
loop. 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]);
}
}
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. 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
You use object.hasOwnProperty(p) to determine if an object has an enumerable property 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.
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.
For example, by default all objects have a 'toString' method, but it will not show up in hasOwnProperty.
hasOwnProperty
is a proper way of checking an object has a property or not. someVar.someProperty
cannot be used as an alternative to this situation. 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')
.
2021 - Object.hasOwn as a replacement for 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.
There is a new alternative method called Object.hasOwn()
and is intended to be a replacement for Object.hasOwnProperty()
Object.hasOwn()
is a static method which returns true if the specified object has the specified property as its own property. If the property is inherited, or does not exist, the method returns 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. 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)
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
Browser compatibility - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility
hasOwnProperty is a normal JavaScript function that takes a string argument.
In your case, somevar.hasOwnProperty('someProperty')
, it checks the somevar
function has somepropery
or not - it returns true and false.
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') ?
The hasOwnProperty()
method returns a boolean
indicating whether the object has the specified property as its own property (as opposed to inheriting it).
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
will return the property value, You can not check that this property is available in the object or not via someVar.someProperty
.
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()
.
For this case someVar is Object. Object has a prototype calls 'hasOwnProperty'. Property means a value for key in Object.
For example:
const objectTest = {key1: property1, key2: property2}
If (objectTest.hasOwnProperty('key1')) {
return true
}
else { return false }
In this case we got true, because key1 has property1.
If you want to check more information for this prototype, you can read there
I'd just like to add that in the case of Object.keys
, you don't need hasOwnProperty
. Only for for (const key in object)
loops.
class Person { name = "foo" }
Person.prototype.age = 25
a = new Person()
console.log(Object.keys(a))
Only prints [ 'name' ]
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:
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. So you can use it like this:
for (const key in objB) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
console.log(objB[key])
}
}
It checks if an object has a property. It works the same as if(obj.prop)
, as far as I know.
本文标签: objectHow and why use hasOwnProperty in JavaScriptStack Overflow
版权声明:本文标题:object - How and why use hasOwnProperty in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736766358a1951841.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论