admin管理员组

文章数量:1287859

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?

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?

Share Improve this question edited Feb 10, 2010 at 1:24 Jacob 78.9k24 gold badges155 silver badges241 bronze badges asked Feb 10, 2010 at 1:01 ChetanChetan 48k31 gold badges110 silver badges146 bronze badges 2
  • 2 There are no classes or class methods in JavaScript – Chris Ballance Commented Feb 10, 2010 at 1:04
  • @Chris Ballance Thats not explicitly true.. – austinheiman Commented Mar 14, 2015 at 2:39
Add a comment  | 

4 Answers 4

Reset to default 7

Use this.init(), but that is not the only problem. Don't call new on your internal functions.

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

    this.run = function() {
        // call init here
        this.init();
    };
}

Test.init();
Test.run();

// etc etc

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

Try this,

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

//creating a new instance of Test
var jj= new Test();
jj.run(); //will give an alert in your screen

Thanks.

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

Unless I'm missing something here, you can drop the "new" from your code.

本文标签: In JavaScripthow do I call a class method from another method in the same classStack Overflow