【问题标题】:In javascript, how do I call a class method from another method in the same class?在javascript中,如何从同一个类中的另一个方法调用一个类方法?
【发布时间】:2011-01-15 01:52:09
【问题描述】:

我有这个:

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

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

【问题讨论】:

  • JavaScript 中没有类或类方法
  • @Chris Ballance 这不是明确真的..

标签: javascript class methods


【解决方案1】:

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

【讨论】:

  • 但是有了这个,我不能从另一个班级打电话给Test.init()。如何使Test 成为单例,但仍然可以通过这种方式调用init()
  • 对我来说很好,萤火虫不会抱怨。您是否从测试内的函数声明中删除了“新”?
  • 你忘了从顶部函数中删除 new... 构造函数
  • 你能用class更新这个ES6的答案吗?我想知道。谢谢!
【解决方案2】:

请尝试这样写:

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】:

    试试这个,

     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
    

    谢谢。

    【讨论】:

      【解决方案4】:
      var Test = function() {
          this.init = function() {
              alert("hello");
          } 
          this.run = function() {
              this.init();
          }
      }
      

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

      【讨论】:

      • 哪个很好……不?
      猜你喜欢
      • 2017-10-17
      • 2023-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-14
      • 1970-01-01
      • 2014-11-07
      相关资源
      最近更新 更多