Calling one method from another in a Javascript class

Boris picture Boris · Dec 1, 2013 · Viewed 9.9k times · Source

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?

Answer

Bas van Dijk picture Bas van Dijk · Dec 1, 2013

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();