Calling one method from another in a Javascript class

10.4k views Asked by At

When defining a class in Javascript, how can I call one method from another one?

exports.myClass = function () {

    this.init = function() {
        myInternalMethod();
    }

    this.myInternalMethod = function() {
        //Do something
    }
}

The code above gives me the following error when executing it:

ReferenceError: myInternalMethod is not defined

I also tried this.myInternalMethod and self.myInternalMethod, but both lead to errors. What's the right way to do this?

3

There are 3 answers

0
Thilo On

this.myInternalMethod() does seem to work, though:

var exports = {};
exports.myClass = function () {

    this.init = function() {
        this.myInternalMethod();
    }

    this.myInternalMethod = function() {
        //Do something
    }
}

var x = new exports.myClass();
x.init();
0
Bas van Dijk On

I have created this fiddle http://jsfiddle.net/VFKkC/ Here you can call myInternalMedod()

var myClass = function () {

    this.init = function() {
        this.myInternalMethod();
    }

    this.myInternalMethod = function() {
        console.log("internal");
    }
}

var c = new myClass();

c.init();
0
AudioBubble On

Is it a private member?

exports.myClass = function () {

    this.init = function() {
        myInternalMethod();
    }

    function myInternalMethod() {
        //Do something
    }
}