hasOwnProperty is not a function in Node.js? - javascript

I am going to test if 'session' property exists:
console.log(queryData)
console.log(typeof queryData)
if ('session' in queryData) {
console.log('in')
}
else {
console.log('not in')
}
if (queryData.hasOwnProperty('session')) {
console.log('has own propety')
}
Its result is:
[Object: null prototype] { session: '0geBdiCsfczLQiT47dd45kWVN2Yp' }
object
in
/home/ubuntu/22.enmsg/cli/main.js:72
if (queryData.hasOwnProperty('session')) {
^
TypeError: queryData.hasOwnProperty is not a function
Why does the hasOwnProperty NOT work?

Most objects in javascript inherit from Object; it's possible to intentionally create objects that inherit from nothing (i.e., null), and therefore they won't have any of the typical methods you'd expect to live on the object.
You would normally know if your code was doing this, so the object might be something passed to you from another library.
A way around the error is to call hasOwnProperty on Object explicitly, and bind it to the object, like so:
// Calls "hasOwnProperty" on queryData, even if queryData has
// no prototype:
console.log(Object.hasOwnProperty.bind(queryData)('session'));
EDIT: Just editing to add an opinion, which is that a much better line for your purposes is the simple truthy check if (queryData.session) {. The vagueness of this check is a strength when what you're asking is "did a session get passed?" - if session is null, undefined, false, empty string, or the key is missing altogether, the answer is clearly "no".

The easiest solution is to convert your null-prototype object to a standard javascript Object. You can do so by:
OBJjavascript = JSON.parse(JSON.stringify(objNullPrototype));

Parsing the object as in https://stackoverflow.com/a/56488323/3121906 would technically work but would be expensive for large objects.
https://stackoverflow.com/a/53978289/3121906 is good, but why not just use call?
Object.prototype.hasOwnProperty.call(queryData, 'session')

Related

Function exists but "undefined". Considered as true when used in condition

Can someone explain to me what is happening in the following code? Thanks.
let myObject = {
myFunction() {
console.log('HELLO WORLD');
}
};
console.log(JSON.stringify(myObject.myFunction));
if (myObject.myFunction) {
console.log('myFunction exists');
}
As described over in MDN, JSON.stringify returns undefined when a function is passed as an argument:
undefined, Functions, and Symbols are not valid JSON values. If any
such values are encountered during conversion they are either omitted
(when found in an object) or changed to null (when found in an array).
JSON.stringify() can return undefined when passing in "pure" values
like JSON.stringify(function(){}) or JSON.stringify(undefined).
Because JSON.stringify() cannot be used on functions, they are treated as undefined. See the explanation here.

Confused about "hasOwnProperty" for detecting existence of functions

I'm sure this is a duplicate, but I couldn't find the right search terms to find an answer.
I'm trying to use hasOwnProperty() to determine if a function exists on an object or not. I know there are other ways to do this, but I want to understand why that method doesn't work the way I was expecting.
I typed this into a Chrome Dev Tools console:
window.hasOwnProperty("getSelection")
<- true
window.getSelection().hasOwnProperty("empty")
<- false
What I don't understand is why hasOwnProperty("empty") returns false, when that method does exist on the Selection object and I can call it.
window.getSelection().empty() // Returns no errors
getSelection returns a Selection object instance, which has an internal prototype of Selection.prototype. The prototype has the empty method on it; it's not on the instance itself:
const sel = window.getSelection();
console.log(
Object.getPrototypeOf(sel) === Selection.prototype,
Selection.prototype.hasOwnProperty("empty")
);
If you wanted to implement this sort of thing yourself:
class Foo {
method() {
console.log('method');
}
}
const f = new Foo();
f.method();
console.log(
f.hasOwnProperty('method'),
Foo.prototype.hasOwnProperty('method')
);
That's because it's not a property on that object, rather it's inherited. Inherited properties are not the object's own properties, as they come from the constructor or class. Far better is the in keyword:
console.log("getSelection" in window);
console.log("empty" in window.getSelection());

JavaScript support for property in obj [duplicate]

I have the following javascript function that fails a jslint check
function hasActiveX() {
return ('ActiveXObject' in window);
}
jslint error
Unexpected 'in'. Compare with undefined, or use the hasOwnProperty method instead.
should I just live with the jslint error, or is there a better way to determine ActiveXObject?
I could not find a jslint flag to skip this check?
Ignore the error. The "in" operator is clearly defined in ECMA 262-5.1 / June 2011 sec-11.8.7
There appear to be only three outcomes for 'someProperty' in anObject which is one of: true, false, or a TypeError exception is thrown. When it evaluates to true, then there is definitely 'someProperty' in anObject. When it evaluates to false there is definitely not 'someProperty' in anObject. When a TypeError is thrown there is definitely not 'someProperty' in anObject because anObject is either null or it isn't an object at all. This all seems very clear to me. When I want to know if an object has a property and, I don't care if that property is the object's own property or being inherited and, I don't care what the value of the property is, then I simply look for 'someProperty' in anObject.
Warning
Caution: some would have you check for anObject.someProperty !== undefined but that isn't really checking whether or not the object has the property. What it's doing is checking whether the object has the property AND that the value of that property is NOT undefined. Some would have you check for anObject.hasOwnProperty('someProperty'); but that will only tell you if the object has that property AND has NOT inherited it somehow. Don't believe me? Try the following:
console.log(document.body.tagName);
// BODY
console.log(document.body.hasOwnProperty('tagName'));
// false, it's inherited
console.log('tagName' in document.body);
// true, it does have the property
document.body.wobbles = undefined;
// new property added to document.body
console.log('wobbles' in document.body);
// true, it does have the property
console.log(document.body.wobbles !== undefined);
// false, the value really IS undefined
I've written an article about the "in" operator that goes into more detail. If you want to read it it's at: http://matthewkastor.blogspot.com/2012/09/Unexpected--in---Compare-with-undefined--or-use-the-hasOwnProperty-method-instead.html The bottom line is that you should just ignore this error and wrap things up in a try catch block if the object might be null or not an object.
function hasProperty(prop, obj) {
try {
return prop in obj;
} catch(e) {
return e;
}
}
I think JSLint is asking you to try:
function hasActiveX() {
return window.hasOwnProperty('ActiveXObject');
}
Or the other suggestion of comparing against "undefined":
return (typeof(window.ActiveXObject) != "undefined");
Personally, I prefer the former.
After reading the comments, it seems like in is actually useful if JSLint would stop complaining about it, otherwise I would try option 2 above.

Generating generic getters and setter on javascript object

It is possible to create getters and setters in javascript as shown by
Object.defineProperty
__define***__
In all those instances, the name of the property is known.
Is it possible create a generic one.
By this I mean, I have a getter and or setter and it is called irrespective of the property name.
Is this possible?
If so, how?
regards.
Note:
I did find these after posting the question. Looks like it is currently not possible as the first answer stated.
Is it possible to implement dynamic getters/setters in JavaScript?
Monitor All JavaScript Object Properties (magic getters and setters)
To all time travelers like me:
It was not possible at the time the question was asked, but it is already possible in present versions of EcmaScript via so-called proxy objects. See more here:
Is it possible to implement dynamic getters/setters in JavaScript?
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
There is a non standard function __noSuchMethod__() which is executed when a non existing property is invoked as a function.
But I don't think there is exactly what you are looking for in JavaScript (yet).
Not possible in standard javascript at this point.
I suppose you are expected to handle this yourself:
if (!object.hasOwnProperty('foo')) {
// object has a foo property, its value might be undefined
} else if (typeof object.foo != 'undefined') {
// there is a foo property elsewhere on object's prototye chain with
// a value other than undefined
} else {
// the foo property might exist on the prototype chain with
// a value of undefined, or might not exist on the chain at all
}
I feel like you guys were looking for something like this
function getterSetter()
{
var valA;
this.set=function (propName,val)
{
if(typeof this[propName] =='function' )
{
return false;
}
this[propName]=val;
}
this.get=function (propName,val)
{
if(typeof this[propName] =='function' )
{
return false;
}
return this[propName];
}
}
Here the set and get methods are setter and getter. You can verify this with following code.
var testObj=new getterSetter();
testObj.set('valA',10);
alert(testObj.get('valA'));
Also, checking for the propName to set/get is not a function.

JavaScript object detection: dot syntax versus 'in' keyword

I have seen two ways of detecting whether a UA implements a specific JS property: if(object.property) and if('property' in object).
I would like to hear opinions on which is better, and most importantly, why. Is one unequivocally better than the other? Are there more than just these two ways to do object property detection? Please cover browser support, pitfalls, execution speed, and such like, rather than aesthetics.
Edit: Readers are encouraged to run the tests at jsperf.com/object-detection
if(object.property)
will fail in cases it is not set (which is what you want), and in cases it has been set to some falsey value, e.g. undefined, null, 0 etc (which is not what you want).
var object = {property: 0};
if(object.isNotSet) { ... } // will not run
if(object.property) { ... } // will not run
if('property' in object)
is slightly better, since it will actually return whether the object really has the property, not just by looking at its value.
var object = {property: 0};
if('property' in object) { ... } // will run
if('toString' in object) { ... } // will also run; from prototype
if(object.hasOwnProperty('property'))
is even better, since it will allow you to distinguish between instance properties and prototype properties.
var object = {property: 0};
if(object.hasOwnProperty('property')) { ... } // will run
if(object.hasOwnProperty('toString')) { ... } // will not run
I would say performance is not that big of an issue here, unless you're checking thousands of time a second but in that case you should consider another code structure. All of these functions/syntaxes are supported by recent browsers, hasOwnProperty has been around for a long time, too.
Edit: You can also make a general function to check for existence of a property by passing anything (even things that are not objects) as an object like this:
function has(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
Now this works:
has(window, 'setTimeout'); // true
even if window.hasOwnProperty === undefined (which is the case in IE version 8 or lower).
It really depends what you want to achieve. Are you talking about host objects (such as window and DOM nodes)? If so, the safest check is typeof, which works for all host objects I know of:
if (typeof object.property != "undefined") { ... }
Notes:
Avoid object.hasOwnProperty() for host objects, because host objects are not obliged to inherit from Object.prototype and therefore may not have a hasOwnProperty() method (and indeed in IE < 9, they generally do not).
A simple Boolean coercion (e.g. if (object.property) { ... }) is a poor test of the existence of a property, since it will give false negatives for falsy values. For example, for an empty textarea, if (textarea.selectionStart) { ... } will not execute the block even though the property exists. Also, some host object properties throw an error in older versions of IE when attempting to coerce to a Boolean (e.g. var xhr = new ActiveXObject("Microsoft.XMLHTTP"); if (xhr.responseXML) { ... }).
The in operator is a better test of the existence of a property, but there are once again no guarantees about support for it in host objects.
I recommend against considering performance for this kind of task. Choose the safest option for your project and only optimize later. There will almost certainly be much better candidates for optimization than property existence checks.
For more background on this, I recommend this excellent article by Peter Michaux.
Definitely if ('property' in object) is the right way to go. That actually tests if the property is in the object (or in its prototype chain, more on that below).
if (object.property) on the other hand, will coerce 'property' into a truth/flase value. If the property is unset, it will return "undefined", which will be coerced into false, and appear to work. But this will also fail for a number of other set values of properties. javascript is notoriously inconsistent in what it treats as truthy and falsy.
Finally, like I said above, 'property' in 'object' will return true if it's in anywhere in the prototype chain. If you want to test that's on the object itself, and not somewhere higher up in the chain, you use the hasOwnProperty method like so:
if (object.hasOwnProperty('property')) ...
The first one would fail if "property" is false of 0. To make sure that there actually exist a property you need to check that object.property !== undefined, or use the in-keyword.
[Edit]
There is also the hasOwnProperty-function, but I've never really used that one so I can't say much about it. Though I think it won't return true if the property is set in a prototype, which sometimes you want, other times you don't want.
This allows you to use window.hasOwnProperty as either referring to itself or something else, regardless of your scripting host.
// No enclosing functions here
if (!('hasOwnProperty' in this))
function hasOwnProperty(obj, prop) {
var method = Object.prototype.hasOwnProperty;
if (prop === undefined)
return method.call(this, obj);
return method.call(obj, prop);
}
//Example of use
var global = global || this; //environment-agnostic way to get the global object
var x = 'blah';
WScript.Echo(global.hasOwnProperty('x') ? 'true' : 'false'); //true
//Use as non-object method
var y = { z: false };
WScript.Echo(hasOwnProperty(y, 'z') ? 'true' : 'false'); //true
WScript.Echo(hasOwnProperty(y, 'w') ? 'true' : 'false'); //false
// true ಠ_ಠ
WScript.Echo(hasOwnProperty(global, 'hasOwnProperty') ? 'true' : 'false');

Categories