Confused about "hasOwnProperty" for detecting existence of functions - javascript

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());

Related

How do I make a JavaScript variable completely immutable?

I've heard similar questions, but not the answer that I wanted;
I do not count const because:
1).
it doesn't actually make it immutable, it only makes the reference immutable
2).
it messes with the scope, and I want it to work outside the block, too
3).
not all browsers support it yet
{
const hello = ["hello", "world"];
hello.push("!!!");
console.log(hello);//outputs "hello", "world", "!!!"
}
//and it doesn't, and shouldn't, work here
console.log(hello);
Just use Object.freeze
const immutableArray = Object.freeze([1,2,4])
You can use Object.freeze for this (obviously only on objects).
const hello = Object.freeze(["hello", "world"]);
// hello.push("!!!");
// will throw "TypeError: can't define array index property past the end of an array with non-writable length"
// hello.length = 0;
// will fail silently
// hello.reverse();
// will throw "TypeError: 0 is read-only"
// hello[0] = "peter";
// will fail silently
From MDN:
The Object.freeze() method freezes an object. A frozen object can no longer be changed; freezing an object prevents new properties from being added to it, existing properties from being removed, prevents changing the enumerability, configurability, or writability of existing properties, and prevents the values of existing properties from being changed. In addition, freezing an object also prevents its prototype from being changed. freeze() returns the same object that was passed in.
However, there is no keyword to define a completely immutable variable without using Object.freeze or Object.seal on the variable's value.
For a less restrictive approach Javascript also has Object.seal().
The way to do it without const is to use Object.defineProperty, and like I wanted, it behaves like var in terms of scope:
{
Object.defineProperty(typeof global === "object" ? global : window, "PI", {
value: Object.seal(3.141593),
enumerable: true,
writable: false,
configurable: false
});
}
console.log(PI); // 3.141593
The only problem is that it that it doesn't throw an error outside of strict mode.

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.

get type of object under prototype function

somebody know how to get typeof object under prototype property? i.e. I have the next code:
Object.prototype.someproperty = function(){
...do something...
console.log(typeof this);
..more...
}
in my code this results alway's "Function" because the constructor of objects is a function. when I call like this
Array.someproperty(); //In this i want get "array"
//or
String.someproperty(); //In this i want get "string"
I want get "Array" instead "function"... somebody know how?
The problem here is that this when called via Array and String is bound to the function and not an instance of the types. The only way I know of to determine which of these functions is being called is to do manual testing like the following
Object.prototype.someproperty = function() {
if (this === Array) {
return "array";
} else if (this === String) {
return "string";
}
...
}
In this case though you're not actually reporting the type of the object the prototype is being invoked from. The value "function" is quite accurate for that. This is more of a heuristic than a true type test
Finally along this time and with a lot of reading and learning, I have seen that it is very bad practice to extend the prototype objects. I thank you all for your support.

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');

Hide method from enumeration

I want to add a method to every object.
When I just set Object.prototype.somefunction = ..., it will come up when somebody enumerates the object using the usual pattern:
for (i in o){
if (o.hasOwnProperty(i)){
// do something with object
}
}
I tried to set it higher up the prototype chain, but that is not possible (at least not possible in Chrome):
TypeError: Cannot set property 'blah' of undefined
Can I set some flag or something on the method so that it won't get enumerated, just like the native methods won't? (Or at least make hasOwnProperty() return false.)
Update: Sorry, I didn't look at it properly. I am using the ExtJS Framework and the object I was looking at had been processed by Ext.apply() which does the following:
for(var p in c){
o[p] = c[p];
}
That's where the "own property" flag gets lost.
So I guess I have no chance (in ECMAScript < 5) to inject a method into all objects that behaves like a native one?
I'm not sure I understand correctly. hasOwnProperty is needed exactly for this case, and enumerating an object via
for (i in o){
if (o.hasOwnProperty(i)){
// do something with object
}
}
should not include methods from Object.prototype. Can you please make a working example where you see this behaviour?
I also do not understand what you mean by
I tried to set it higher up the
prototype chain
as Object.prototype is the root of the chain, so you cannot get any higher.
In short, the solution is doing exactly what you claim you have done. If this does not work, probably you have made a mistake or found a bug.
I'm not sure what you mean. If a method/property is attached to the prototype, hasOwnProperty will return false. See this code:
function Con(){this.enumerableProp = true;};
Con.prototype.fun = function(){return 'that\'s funny'};
var fun = new Con;
alert(fun.hasOwnProperty('fun')); //=> false
alert(fun.hasOwnProperty('enumerableProp')); //=> true
So, what do you mean?
Make a base class and make all other classes extend it. Add the method to the base class.
ES5 has Object.getOwnPropertyNames() for this:
Object.prototype.lolwat = 42;
var obj = {
'foo': 1,
'bar': 2
};
Object.getOwnPropertyNames(obj); // ['bar', 'foo']
To see where it is supported: http://kangax.github.com/es5-compat-table/
However, for-in combined with a hasOwnProperty check should work too.
You get that error because there is nothing higher up the prototype chain.
Of note also is that adding to Object's prototype is not really recommended unless absolutely necessary for some reason
Edit: actually, my original answer was incorrect - as the others have pointed out, your object should not have that as own property if it's in Object's prototype.
In any case, if you want to create a prototype chain (or more importantly, avoid changing Object's prototype), you'll want to create your own class:
function MyBaseClass(){
}
MyBaseClass.prototype = new Object();
MyBaseClass.prototype.someMethod = function() { /* your method */ };
var o = new MyBaseClass();
o.hasOwnProperty('someMethod') //should be false

Categories