Calling a method from inside my constructor that is defined outside of it

Discussion in 'JavaScript' started by willjones, May 21, 2008.

  1. #1
    I have declared a function that I am using like a class... See below.

    (I read that it is good to declare methods for your (class) function outside with MyClass.prototype.myMethod = function() {} so that instances of the class can share the method code in memory. So I wanted to continue doing this.)

    function MyClass()
    {
    // I want to call this.myMethod(); from inside this constructor, but I can't because it isn't defined yet!
    }

    MyClass.prototype.myMethod = function doSomething() { alert('hi'); }

    I want to be able to call myMethod from inside the constructor, but it won't work because it isn't defined yet. Is there a way to declare all my methods before the function MyClass() line so that I can use them from inside the constructor if I want?

    Please help...

    Thanks,
    Will
     
    willjones, May 21, 2008 IP
  2. willjones

    willjones Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    OK, I finally discovered how to do this...

    function MyClass()
    {
    if ( this.myMethod!=null ) this.myMethod();
    }

    MyClass.prototype.myMethod = function doSomething() { alert('hi'); }

    Thanks,
    Will
     
    willjones, May 22, 2008 IP