views:

68

answers:

3

I was reading through this thread: http://stackoverflow.com/questions/61088/hidden-features-of-javascript and found this post: http://stackoverflow.com/questions/61088/hidden-features-of-javascript/61260#61260

I was playing around with the code in firebug and I found that this bit of code seems to work fine:

var fn = function(x) {
   console.log(this.foo);
}
fn.foo = 1;

How come I can access the property of the function before it's assigned?

A: 

if it was not defined you could access it anyway, it would just have the value undefined.

I guess you call fn(x) after the fn.foo = 1; statement. if you call it before, you will log undefined after, you log 1.

mathroc
+2  A: 

The return value 1 is not from console.log(this.foo),

Its from fn.foo = 1, firebug just return last value in its console

Try this, you will see also 1 too

fn=function(){}
fn.foo = 1;
S.Mark
Oh I see. So is this a firebug glitch or is this javascript doing something funky?
Yansky
@Yansky: Neither. It's feature-by-design. The last return value is always printed.
KennyTM
+1  A: 

Because that function isn't executed when you assign it to fn. A variable is resolved in execution time.

Even without the fn.foo = 1; line, getting an undefined property from an object returns undefined anyway. That's not an error.

Also, this.foo will not print 1 when you run fn(), because this inside the function does not point to the function fn, but window, or the instance that receives a new fn().

KennyTM