Javascript 在javascript中,如何从同一个类中的另一个方法调用一个类方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2233710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:22:56  来源:igfitidea点击:

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

javascriptclassmethods

提问by Chetan

I have this:

我有这个:

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

I want to call initwithin run. How do I do this?

我想init在运行中调用。我该怎么做呢?

采纳答案by Jeff B

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

使用this.init(),但这不是唯一的问题。不要在内部函数上调用 new。

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

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

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

// etc etc

回答by Zhube

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

回答by Nazmul

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.

谢谢。

回答by Mike Sherov

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.

除非我在这里遗漏了一些东西,否则您可以从代码中删除“新”。