0

I was reading through this thread: Hidden Features of JavaScript? and found this post: Hidden Features of JavaScript?

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?

Community
  • 1
  • 1
Yansky
  • 4,580
  • 8
  • 29
  • 24

3 Answers3

2

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;
YOU
  • 120,166
  • 34
  • 186
  • 219
1

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
  • 510,854
  • 105
  • 1,084
  • 1,005
0

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.

Mathieu
  • 5,495
  • 2
  • 31
  • 48