tags:

views:

66

answers:

3

Why is it that I can do the following in javascript:

function a() {};
a.foo = 30;

Specifically, why can I set a property on the function a? After all, I cannot do this:

var a = 20;
a.foo = 30;
+3  A: 

You really can't do this because it's a syntax error

function a = function() {};

I suppose you simply want to say:

function a() {}

Anyway. The reason that you cannot get a property out of a number, is that it is not a real Object.

a = 20;
a.foo = 30;   // this works
asert(a.foo); // this alerts nothing

Believe it or not, the same goes for strings:

a = "ohai";
a.foo = 30;   // this works
asert(a.foo); // this alerts nothing

However if it's String object, then it works as expected:

a = new String("ohai");
a.foo = 30;   // this works
asert(a.foo); // this alerts 30

Or if it's an Number object. You get the point.

String and number literals are not objects in Javascript. That's the reason.

gugod
A: 

In javascript functions are objects. Or they inherit from objects, or something.

try doing

a = function(){};
alert(typeof a.prototype);
david
+1  A: 

In JavaScript the dot (.) operator expects it's left value to be an object. And in JavaScript, functions are objects.

Basically, in JavaScript, there are four main datatypes:

  1. Number
  2. String
  3. Boolean
  4. Object

Objects encompasses functions, arrays, date objects, and (for lack of a better word) regular objects. The function object is unique in that it contains executable code, and can be invoked.

Numbers are primitives, and thus you cannot access/assign properties to/from them.

Christopher Scott
there's Arrays too... they have different native prototypes than Objects (note that an Array will return a typeof as an object, but if you check its constructor you will see that it is in fact `Array`).
Peter Ajtai
@Peter: Still, Arrays are objects. The ECMA standard defines "Array objects", "Function objects", ... and "Object objects"
Pumbaa80
@Pumbaa - Thanks. That explains the `typeof`.
Peter Ajtai