javascript If functions are objects then why doesn't this work
var foo = function () { this.bar = 1; }
>开发者_如何学Go> foo.bar
undefined
How do I access the property of a function?
You syntax is wrong:
function foo() { this.bar = 1; }
var a = new foo();
a.bar; // 1
That is a definition. You need to instantiate it.
var foo = function () { this.bar = 1; }
>> new foo().bar
Another option:
var foo = function () { this.bar = 10; return this; } ();
console.log(foo.bar);
Read about self executing functions here:
What is the purpose of a self executing function in javascript?
The problem here is that you've only defined foo
and not actually executed it. Hence the line this.bar = 1
hasn't even run yet and there is no way for bar
to be defined.
The next problem is that when you run foo
it will need a context which this
will be defined in. For example
var x = {}
foo.apply(x);
x.bar === 1 // true
Or alternatively you could run foo
as a constructor and access bar
on the result
var x = new foo();
x.bar === 1 // true
精彩评论