-4

I have the following code:

function MyFunction () {
   this.my_method1 = function () {};
   this.my_method2 = function () {};
}

How can I access this.my_method1 in this.my_method2. I have tried using:

  • this.my_method1()
  • MyFunction.my_method1()
  • my_method1()

but none seem to work. Help?

Kill Bill
  • 7
  • 2
  • 1
    this.my_method1() is at least syntactically ok. the others are not. if you want more help, you'll need to define "not work" – gefei Nov 24 '15 at 09:56
  • I am trying to use it like this in my_method2: var b = this.my_method1(); Is this even possible? – Kill Bill Nov 24 '15 at 10:04
  • it depends on how my_method2 is called. In order to understand `this`, you may want to have a look at http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – gefei Nov 24 '15 at 10:04

1 Answers1

0

The MyFunction function is basically a constructor. Therefore, to access methods you need to create an object out of it:

var foo = new MyFunction();
foo.my_method1();
foo.my_method2();
slebetman
  • 93,070
  • 18
  • 116
  • 145