get all methods and properties of an object - javascript

If I use (on a text frame):
b.selection().fit(FitOptions.frameToContent);
Then it works as expected, this means that the selected object has a fit method.
If I use:
for (var property in b.selection()) {
b.println(property);
}
On the same selection then it doesn't print a fit method.
If I use this:
function getMethods(obj) {
var result = [];
for (var id in obj) {
try {
if (typeof(obj[id]) == "function") {
result.push(id + ": " + obj[id].toString());
}
} catch (err) {
result.push(id + ": inaccessible");
}
}
return result;
}
b.println(getMethods(b.selection()));
Then I don't get the fit method either. And I would really like to know all methods and properties of the selected object. So how do i get them?

try obj.reflect.methods to get all methods

When method fit() exists and doesn't shine up in the for-in-loop it is a non-enumerable property.
There are different ways to access the properties of an object:
var obj = b.selection();
for (var p in obj) {
console.log(p); // --> all enumerable properties of obj AND its prototype
}
Object.keys(obj).forEach(function(p) {
console.log(p); // --> all enumerable OWN properties of obj, NOT of its prototype
});
Object.getOwnPropertyNames(obj).forEach(function(p) {
console.log(p); // all enumerable AND non-enumerable OWN properties of obj, NOT of its prototype
});
If you don't find .fit() on one of this ways its not enumerable AND not OWN property of obj, but sits somewhere in the prototype of obj. Then you can do:
var prot = Object.getPrototypeOf(obj);
Object.getOwnPropertyNames(prot).forEach(function(pp) {
console.log(pp); // --> all enumerable AND non-enumerable properties of obj's prototype
});
Often objects have a bit longer prototype-chain and the property sits somewhere deeper on it. Then you just repeat the last snippet as often as needed:
var prot2 = Object.getPrototypeOf(prot);
Object.getOwnPropertyNames(prot2).forEach( /*...*/ );
To make it complete: Let's say you have found .fit on the obj's prototype prot. Then you can inspect it:
console.log(Object.getOwnPropertyDescriptor(prot.fit));
That outputs an object which shows the value of prot.fit and whether it's enumerable, writable, and configurable or not. The Object.methods and some more FIND HERE.

Or just use b.inspect(obj). Prints out all properties and values of an object in a recursive manner to the console. See http://basiljs.ch/reference/#inspect

Related

Does the spread operator not copy over the prototype?

The following code does not appear to copy over an object's prototype.
const animalProto = {
eat() {
// function body
},
sleep() {
// function body
},
}
function animalCreator(proto, attributes) {
return {...Object.create(proto), ...attributes}
}
const cat = animalCreator(animalProto, { name: 'garfield' })
cat.eat() // this is an error; function is not defined; it doesn't appear to link the prototype chain.
If I replace the spread with the following it works:
return Object.assign(Object.create(proto), attributes)
Essentially my question is why does Object.assign work but not the spread operator. Is there something Object.assign is doing that the spread operator is missing?
See the docs:
It copies own enumerable properties from a provided object onto a new object.
"Own enumerable" means that properties on the prototype will not be included.
If you spread an object with inherited properties (such as an object immediately created with Object.create), none of those inherited properties will be present in the result.
Object.assign is slightly different - it assigns all properties to the right of the first to the first. It would be more similar to spread if you had passed an empty object as the first argument:
return Object.assign({}, Object.create(proto), attributes)
in which case nothing in proto would be reflected in the output.
const proto = { foo: 'bar' };
const result = Object.assign({}, Object.create(proto), { another: 'prop' });
console.log(result);
Object.create() makes a new object that is prototype linked to the object passed to it. This means that the returned object doesn't get a copy of the parent's attributes, it just has a link to the parent prototype. The object spread only copies the objects own enumerable properties, which doesn't include those up the prototype chain.
const animalProto = {
eat() {
// function body
},
sleep() {
// function body
},
}
let o = Object.create(animalProto)
// o doesn't have it's own eat or sleep.
console.log(Object.getOwnPropertyNames(o))
console.log({...o}) // empty

What are the possible errors in this Object merging function?

I set out to find and understand a nice way to merge objects in Vanilla JS. My requirements for the function are very simple (borrowed from here):
Merge two objects x and y deeply, returning a new merged object with the elements from both x and y.
If an element at the same key is present for both x and y, the value from y will appear in the result.
The merge is immutable, so neither x nor y will be modified.
I came across this article that seems to provide a pretty good solution. After going through the code and understanding it (for the most part), I shortened it down to the following:
var extend = function() {
var extended = {};
var length = arguments.length;
// Merge the object into the extended object
var merge = function(obj) {
for (var prop in obj) {
//Check if a property is an object and another layer of merging is required
if (Object.prototype.toString.call(obj[prop]) === '[object Object]') {
extended[prop] = extend(true, extended[prop], obj[prop]);
} else {
extended[prop] = obj[prop];
}
}
};
// Loop through each object and conduct a merge
while (length--) {
var obj = arguments[length];
merge(obj);
}
return extended;
};
From the original solution I removed the check for a deep merge as I would like to deep merge by default, and this line, present before the currently merged property value is checked for being an object:
if ( Object.prototype.hasOwnProperty.call( obj, prop ) )
I don't understand this line - why should we check if the object whose properties are currently being looped through has the property from the current loop? I feel like I'm missing something.
So that's it. Are there any cases where this function wouldn't fulfil my requirements? Or break execution on any other way? Thank you.
if ( Object.prototype.hasOwnProperty.call( obj, prop ) )
I don't understand this line - why should we check if the object whose properties are currently being looped through has the property from the current loop?
Because for-in loops visit all of the enumerable properties of an object, including ones it inherits from its prototype. Whether you want to copy inherited properties over depends on your use cases for your extend function. Apparently in the original code, they didn't want to.
Example showing the difference:
var name;
var p = {inherited: "property"};
// Create an object using p as its prototype
var o = Object.create(p);
o.own = "property";
console.log("Without check");
for (name in o) {
console.log("- " + name);
}
console.log("With check");
for (name in o) {
if (Object.prototype.hasOwnProperty.call(o, name)) {
console.log("- " + name);
}
}

javascript- Not outputting the result on console (level beginner) [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 6 years ago.
How do I enumerate the properties of a JavaScript object?
I actually want to list all the defined variables and their values, but I've learned that defining a variable actually creates a property of the window object.
Simple enough:
for(var propertyName in myObject) {
// propertyName is what you want
// you can get the value like this: myObject[propertyName]
}
Now, you will not get private variables this way because they are not available.
EDIT: #bitwiseplatypus is correct that unless you use the hasOwnProperty() method, you will get properties that are inherited - however, I don't know why anyone familiar with object-oriented programming would expect anything less! Typically, someone that brings this up has been subjected to Douglas Crockford's warnings about this, which still confuse me a bit. Again, inheritance is a normal part of OO languages and is therefore part of JavaScript, notwithstanding it being prototypical.
Now, that said, hasOwnProperty() is useful for filtering, but we don't need to sound a warning as if there is something dangerous in getting inherited properties.
EDIT 2: #bitwiseplatypus brings up the situation that would occur should someone add properties/methods to your objects at a point in time later than when you originally wrote your objects (via its prototype) - while it is true that this might cause unexpected behavior, I personally don't see that as my problem entirely. Just a matter of opinion. Besides, what if I design things in such a way that I use prototypes during the construction of my objects and yet have code that iterates over the properties of the object and I want all inherited properties? I wouldn't use hasOwnProperty(). Then, let's say, someone adds new properties later. Is that my fault if things behave badly at that point? I don't think so. I think this is why jQuery, as an example, has specified ways of extending how it works (via jQuery.extend and jQuery.fn.extend).
Use a for..in loop to enumerate an object's properties, but be careful. The enumeration will return properties not just of the object being enumerated, but also from the prototypes of any parent objects.
var myObject = {foo: 'bar'};
for (var name in myObject) {
alert(name);
}
// results in a single alert of 'foo'
Object.prototype.baz = 'quux';
for (var name in myObject) {
alert(name);
}
// results in two alerts, one for 'foo' and one for 'baz'
To avoid including inherited properties in your enumeration, check hasOwnProperty():
for (var name in myObject) {
if (myObject.hasOwnProperty(name)) {
alert(name);
}
}
Edit: I disagree with JasonBunting's statement that we don't need to worry about enumerating inherited properties. There is danger in enumerating over inherited properties that you aren't expecting, because it can change the behavior of your code.
It doesn't matter whether this problem exists in other languages; the fact is it exists, and JavaScript is particularly vulnerable since modifications to an object's prototype affects child objects even if the modification takes place after instantiation.
This is why JavaScript provides hasOwnProperty(), and this is why you should use it in order to ensure that third party code (or any other code that might modify a prototype) doesn't break yours. Apart from adding a few extra bytes of code, there is no downside to using hasOwnProperty().
The standard way, which has already been proposed several times is:
for (var name in myObject) {
alert(name);
}
However Internet Explorer 6, 7 and 8 have a bug in the JavaScript interpreter, which has the effect that some keys are not enumerated. If you run this code:
var obj = { toString: 12};
for (var name in obj) {
alert(name);
}
If will alert "12" in all browsers except IE. IE will simply ignore this key. The affected key values are:
isPrototypeOf
hasOwnProperty
toLocaleString
toString
valueOf
To be really safe in IE you have to use something like:
for (var key in myObject) {
alert(key);
}
var shadowedKeys = [
"isPrototypeOf",
"hasOwnProperty",
"toLocaleString",
"toString",
"valueOf"
];
for (var i=0, a=shadowedKeys, l=a.length; i<l; i++) {
if map.hasOwnProperty(a[i])) {
alert(a[i]);
}
}
The good news is that EcmaScript 5 defines the Object.keys(myObject) function, which returns the keys of an object as array and some browsers (e.g. Safari 4) already implement it.
In modern browsers (ECMAScript 5) to get all enumerable properties you can do:
Object.keys(obj)
(Check the link to get a snippet for backward compatibility on older browsers)
Or to get also non-enumerable properties:
Object.getOwnPropertyNames(obj)
Check ECMAScript 5 compatibility table
Additional info:
What is a enumerable attribute?
I think an example of the case that has caught me by surprise is relevant:
var myObject = { name: "Cody", status: "Surprised" };
for (var propertyName in myObject) {
document.writeln( propertyName + " : " + myObject[propertyName] );
}
But to my surprise, the output is
name : Cody
status : Surprised
forEach : function (obj, callback) {
for (prop in obj) {
if (obj.hasOwnProperty(prop) && typeof obj[prop] !== "function") {
callback(prop);
}
}
}
Why? Another script on the page has extended the Object prototype:
Object.prototype.forEach = function (obj, callback) {
for ( prop in obj ) {
if ( obj.hasOwnProperty( prop ) && typeof obj[prop] !== "function" ) {
callback( prop );
}
}
};
for (prop in obj) {
alert(prop + ' = ' + obj[prop]);
}
Simple JavaScript code:
for(var propertyName in myObject) {
// propertyName is what you want.
// You can get the value like this: myObject[propertyName]
}
jQuery:
jQuery.each(obj, function(key, value) {
// key is what you want.
// The value is in: value
});
Here's how to enumerate an object's properties:
var params = { name: 'myname', age: 'myage' }
for (var key in params) {
alert(key + "=" + params[key]);
}
I found it... for (property in object) { // do stuff } will list all the properties, and therefore all the globally declared variables on the window object..
You can use the for of loop.
If you want an array use:
Object.keys(object1)
Ref. Object.keys()
If you are using the Underscore.js library, you can use function keys:
_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]
Python's dict has 'keys' method, and that is really useful. I think in JavaScript we can have something this:
function keys(){
var k = [];
for(var p in this) {
if(this.hasOwnProperty(p))
k.push(p);
}
return k;
}
Object.defineProperty(Object.prototype, "keys", { value : keys, enumerable:false });
EDIT: But the answer of #carlos-ruana works very well. I tested Object.keys(window), and the result is what I expected.
EDIT after 5 years: it is not good idea to extend Object, because it can conflict with other libraries that may want to use keys on their objects and it will lead unpredictable behavior on your project. #carlos-ruana answer is the correct way to get keys of an object.
If you're trying to enumerate the properties in order to write new code against the object, I would recommend using a debugger like Firebug to see them visually.
Another handy technique is to use Prototype's Object.toJSON() to serialize the object to JSON, which will show you both property names and values.
var data = {name: 'Violet', occupation: 'character', age: 25, pets: ['frog', 'rabbit']};
Object.toJSON(data);
//-> '{"name": "Violet", "occupation": "character", "age": 25, "pets": ["frog","rabbit"]}'
http://www.prototypejs.org/api/object/tojson
I'm still a beginner in JavaScript, but I wrote a small function to recursively print all the properties of an object and its children:
getDescription(object, tabs) {
var str = "{\n";
for (var x in object) {
str += Array(tabs + 2).join("\t") + x + ": ";
if (typeof object[x] === 'object' && object[x]) {
str += this.getDescription(object[x], tabs + 1);
} else {
str += object[x];
}
str += "\n";
}
str += Array(tabs + 1).join("\t") + "}";
return str;
}

if (key in object) or if(object.hasOwnProperty(key)

Do the following two statements produce the same output? Is there any reason to prefer one way to the other?
if (key in object)
if (object.hasOwnProperty(key))
Be careful - they won't produce the same result.
in will also return true if key gets found somewhere in the prototype chain, whereas Object.hasOwnProperty (like the name already tells us), will only return true if key is available on that object directly (its "owns" the property).
I'l try to explain with another example.
Say we have the following object with two properties:
function TestObj(){
this.name = 'Dragon';
}
TestObj.prototype.gender = 'male';
Let's create instance of TestObj:
var o = new TestObj();
Let's examine the object instance:
console.log(o.hasOwnProperty('name')); // true
console.log('name' in o); // true
console.log(o.hasOwnProperty('gender')); // false
console.log('gender' in o); // true
Conclusion:
in operator returns true always, if property is accessible by the object, directly or from the prototype
hasOwnProperty() returns true only if property exists on the instance, but not on its prototype
If we want to check that some property exist on the prototype, logically, we would say:
console.log(('name' in o) && !o.hasOwnProperty('name')); //false
console.log(('gender' in o) && !o.hasOwnProperty('gender')); //true - it's in prototype
Finally:
So, regarding to statement that these two conditions ...
if (key in object)
if (object.hasOwnProperty(key))
...produce the same result, the answer is obvious, it depends.
in will also check for inherited properties, which is not the case for hasOwnProperty.
In summary, hasOwnProperty() does not look in the prototype while in does look in the prototype.
Taken from O'Reilly High Performance Javascript:
You can determine whether an object has an instance member with a
given name by using the hasOwnProperty() method and passing in the
name of the member. To determine whether an object has access to a
property with a given name, you can use the in operator. For example:
var book = {
title: "High Performance JavaScript",
publisher: "Yahoo! Press"
};
alert(book.hasOwnProperty("title")); //true
alert(book.hasOwnProperty("toString")); //false
alert("title" in book); //true
alert("toString" in book); //true
In this code, hasOwnProperty() returns true when “title” is passed in
because title is an object instance; the method returns false when
“toString” is passed in because it doesn’t exist on the instance. When
each property name is used with the in operator, the result is true
both times because it searches the instance and prototype.
You got some really great answers.
I just want to offer something that will save you the need for checking "hasOwnProperty" while iterating an object.
When creating an object usually people will create it in this way:
const someMap = {}
// equivalent to: Object.create(Object.prototype)
// someMap.constructor will yield -> function Object() { [native code] }
Now, if you want to iterate through "someMap" you will have to do it this way:
const key
for(key in someMap ){
if (someMap.hasOwnProperty(key)) {
// Do something
}
}
We are doing so in order to avoid iterating over inherited properties.
If you intend to create a simple object that will only be used as a "map" (i.e. key - value pairs) you can do so like that:
const newMap = Object.create(null);
// Now, newMap won't have prototype at all.
// newMap.constructor will yield -> undefined
So now it will be safe to iterate like this:
for(key in cleanMap){
console.log(key + " -> " + newMap [key]);
// No need to add extra checks, as the object will always be clean
}
I learned this awesome tip here
The other form (called for in) enumerates the property names (or keys)
of an object. On each iteration, another property name string from the
object is assigned to the variable. It is usually necessary to test
object.hasOwnProperty(variable) to determine whether the property name
is truly a member of the object or was found instead on the prototype chain.
for (myvar in obj) {
if (obj.hasOwnProperty(myvar)) { ... } }
(from Crockford's Javascript: The Good Parts)
As other answers indicated, hasOwnProperty will check for an object own properties in contrast to in which will also check for inherited properties.
New method 2021 - Object.hasOwn() as a replacement for Object.hasOwnProperty()
Object.hasOwn() is intended as a replacement for Object.hasOwnProperty() and is a new method available to use (yet still not fully supported by all browsers like as you can see here - https://caniuse.com/?search=hasOwn
)
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
Another way to have only ownproperties is :
<script type="text/javascript">"use strict";
const obj = Object.create({cle:"valeur"});
obj.a = "aaa";
obj.b = "bbb";
obj.c = "ccc";
for(let key=0 ; key < Object.keys(obj).length ; key++){
if(Object.keys(obj)[key]==="cle")
console.log(key , Object.keys(obj)[key] , Object.values(obj)[key]);
// none
if(Object.keys(obj)[key]==="b")
console.log(key , Object.keys(obj)[key] , Object.values(obj)[key]);
// 1 'b' 'bbb'
console.log(key , Object.keys(obj)[key] , Object.values(obj)[key]);
// 0 'a' 'aaa'
// 1 'b' 'bbb'
// 2 'c' 'ccc'
}
console.log(Object.getOwnPropertyDescriptor(obj,"cle"));
// undefined
console.log(Object.getOwnPropertyDescriptor(obj,"c"));
// {value:'ccc', writable:true, enumerable:true, configurable:true}
</script>
The first version is shorter (especially in minified code where the variables are renamed)
a in b
vs
b.hasOwnProperty(a)
Anyway, as #AndreMeinhold said, they do not always produce the same result.

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')?
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?
hasOwnProperty 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!
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
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]);
}
}
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').
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
}
}
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
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().
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.

Categories