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

雨燕双飞 提交于 2019-12-21 03:57:37

问题


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?


回答1:


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



回答2:


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



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/2233710/in-javascript-how-do-i-call-a-class-method-from-another-method-in-the-same-clas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!