简体   繁体   English

在Javascript类中从另一个方法调用一个方法

[英]Calling one method from another in a Javascript class

When defining a class in Javascript, how can I call one method from another one? 用Javascript定义类时,如何从另一个方法调用一个方法?

exports.myClass = function () {

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

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

The code above gives me the following error when executing it: 上面的代码在执行时给我以下错误:

ReferenceError: myInternalMethod is not defined ReferenceError:未定义myInternalMethod

I also tried this.myInternalMethod and self.myInternalMethod, but both lead to errors. 我也尝试了this.myInternalMethod和self.myInternalMethod,但是两者都导致错误。 What's the right way to do this? 什么是正确的方法?

I have created this fiddle http://jsfiddle.net/VFKkC/ Here you can call myInternalMedod() 我创建了这个小提琴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();

this.myInternalMethod() does seem to work, though: this.myInternalMethod()确实可以工作:

var exports = {};
exports.myClass = function () {

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

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

var x = new exports.myClass();
x.init();

Is it a private member? 是私人会员吗?

exports.myClass = function () {

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

    function myInternalMethod() {
        //Do something
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM