开发者

Accessing javascript function properties before they are defined?

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 fir开发者_如何学编程ebug 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?


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;


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜