簡體   English   中英

在javascript中,如何從同一個類中的另一個方法調用類方法?

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

我有這個:

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

我想在運行中調用init 我該怎么做呢?

使用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

相反,嘗試這樣寫:

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

試試這個,

 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

謝謝。

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

除非我在這里遺漏了什么,否則你可以從你的代碼中刪除“新”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM