Ben
Ben

Reputation: 21

javascript If functions are objects then why doesn't this work

var foo = function () { this.bar = 1; }

>> foo.bar 
undefined

How do I access the property of a function?

Upvotes: 1

Views: 57

Answers (4)

ScottE
ScottE

Reputation: 21630

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?

Upvotes: 0

JaredPar
JaredPar

Reputation: 754655

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

Upvotes: 0

Alex Turpin
Alex Turpin

Reputation: 47776

That is a definition. You need to instantiate it.

var foo = function () { this.bar = 1; }

>> new foo().bar

Upvotes: 1

Joe
Joe

Reputation: 82594

You syntax is wrong:

function foo() {  this.bar = 1; }
var a = new foo();
a.bar; // 1

Upvotes: 1

Related Questions