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
  • 77,580
  • 18
  • 124
  • 143
1

That is a definition. You need to instantiate it.

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

>> new foo().bar
Alex Turpin
  • 45,503
  • 23
  • 111
  • 144
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
  • 703,665
  • 143
  • 1,211
  • 1,438
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,265
  • 18
  • 93
  • 130