Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In javascript, how do I call a class method from another method in the same class?

I have this:

var Test = new function() {  
    this.init = new function() {  
        alert("hello");  
    }
    this.run = new function() {  
        // call init here  
    }  
}

I want to call init within run. How do I do this?

like image 639
Chetan Avatar asked Feb 10 '10 01:02

Chetan


People also ask

How do you call a method from another method in the same class?

Example: public class CallingMethodsInSameClass { // Method definition performing a Call to another Method public static void main(String[] args) { Method1(); // Method being called. Method2(); // Method being called. } // Method definition to call in another Method public static void Method1() { System. out.

How do you call a method inside a class in JavaScript?

var test = new MyObject(); and then do this: test. myMethod();

How do you call a class method without creating an object in JavaScript?

Use the static keyword.


1 Answers

Instead, try writing it this way:

function test() {
    var self = this;
    this.run = function() {
        console.log(self.message);
        console.log("Don't worry about init()... just do stuff");
    };

    // Initialize the object here
    (function(){
        self.message = "Yay, initialized!"
    }());
}

var t = new test();
// Already initialized object, ready for your use.
t.run()
like image 114
Zhube Avatar answered Sep 18 '22 13:09

Zhube