【问题标题】:Calling one method from another in a Javascript class在 Javascript 类中从另一个方法调用一个方法
【发布时间】:2023-04-09 10:08:01
【问题描述】:

在 Javascript 中定义一个类时,如何从另一个方法调用一个方法?

exports.myClass = function () {

    this.init = function() {
        myInternalMethod();
    }

    this.myInternalMethod = function() {
        //Do something
    }
}

上面的代码在执行时给了我以下错误:

ReferenceError: myInternalMethod 未定义

我也试过this.myInternalMethod和self.myInternalMethod,但都导致错误。 这样做的正确方法是什么?

【问题讨论】:

  • this 的值缓存在更高范围的变量中,然后使用它。 var self = this; self.method();
  • 另外,JavaScript 没有类。它是一种基于原型的面向对象语言。
  • @elclanrs 你必须知道这是一个非常糟糕的主意,除非你真的想总是引用最后一个实例化的对象。也就是说,这个问题并没有充分的解释......
  • @elclanrs:这解决了我的问题。你介意用这个来回答吗?

标签: javascript node.js class methods referenceerror


【解决方案1】:

我已经创建了这个小提琴http://jsfiddle.net/VFKkC/在这里你可以调用myInternalMedod()

var myClass = function () {

    this.init = function() {
        this.myInternalMethod();
    }

    this.myInternalMethod = function() {
        console.log("internal");
    }
}

var c = new myClass();

c.init();

【讨论】:

    【解决方案2】:

    this.myInternalMethod() 似乎确实有效:

    var exports = {};
    exports.myClass = function () {
    
        this.init = function() {
            this.myInternalMethod();
        }
    
        this.myInternalMethod = function() {
            //Do something
        }
    }
    
    var x = new exports.myClass();
    x.init();
    

    【讨论】:

      【解决方案3】:

      是私人会员吗?

      exports.myClass = function () {
      
          this.init = function() {
              myInternalMethod();
          }
      
          function myInternalMethod() {
              //Do something
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-10-17
        • 2015-12-01
        • 1970-01-01
        • 2011-01-15
        • 1970-01-01
        • 2012-10-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多