Given var x, what is the best way to determine if x can have properties? Can I just do
if(x instanceof Object)
Is that sufficient to ensure that x can have properties or do I need to check for anything else? I know primitives can't have properties but is there anything else? I've been going through checking various types:
var a = false;
a.foo = "bar";
console.log(a["foo"]);
// Logs undefined
var b = "b";
b.foo = "bar";
console.log(b["foo"]);
// Logs undefined
var c = new Array(1,2,3);
c.foo = "bar";
console.log(c["foo"]);
// Logs bar
var d = new Object();
d.foo = "bar";
console.log(d["foo"]);
// Logs bar
var e = new RegExp("");
e.foo = "foo";
console.log(e["bar"]);
// Logs bar
var f = new Number(1);
f.foo = "bar";
console.log(f["foo"]);
// Logs bar
var g = function(){};
g.foo = "bar";
console.log(g["foo"]);
// Logs bar
etc..
Yes, that is sufficient. Note: String can also accept properties, which you are not checking for:
var a = new String("hello");
a.foo = "bar";
But since String instanceof Object == true you should be fine.
For fun, try this (it works, since /x/ instanceof Object == true):
var x = /hello/;
x.foo = "bar";
Another note: your instanceof check will catch this, but I want you to be aware that while normal a javascript function is an Object, a closure (function() { })() is not necessarily an Object, but it might be depending on the value it returns.
Hope that helps.
-tjw
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With