treaint
treaint

Reputation: 709

What Javascript types can have properties?

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..

Upvotes: 3

Views: 214

Answers (2)

Travis Webb
Travis Webb

Reputation: 15018

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

Upvotes: 3

Jeremy Conley
Jeremy Conley

Reputation: 934

You need to create a JavaScript object first like so:

<script>
var foo = {};
foo.bar = 'test';
console.log(foo.bar);
</script>

Vars a and b are just plain ole variables. The var foo = {}; bit is similar to a builtin object called foo and you created an instance like var bar = new foo();

Upvotes: -1

Related Questions