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

>> foo.bar 
undefined

How do I access the property of a function?

Ben
  • 23
  • 2

4 Answers4

1

You syntax is wrong:

function foo() {  this.bar = 1; }
var a = new foo();
a.bar; // 1
Joe
  • 80,724
  • 18
  • 127
  • 145
1

That is a definition. You need to instantiate it.

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

>> new foo().bar
Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
0

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
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
0

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?

Community
  • 1
  • 1
ScottE
  • 21,530
  • 18
  • 94
  • 131