Javascript:从同一个类的另一个方法访问类方法

时间:2014-03-04 14:07:26

标签: javascript oop

新手到javascript中的类并不能解决这个问题。实际上,另一种方法可以返回一个回调构造函数然后我可以从那里调用一个方法,但也许有一个更简单的方法?

function sample() {} //constructor

sample.prototype = {
    onemethod: function () {},
    anothermethod: function () {
        onemethod(); //Doesn't work
        this.onemethod(); //Still the same
    }
}

1 个答案:

答案 0 :(得分:0)

要使其正常工作,您需要正确使用它。需要通过new调用构造函数。

var s = new sample();
s.anothermethod();
// identical to
sample.anothermethod.apply(s);

这样,this将代表s(这是外部背景,通常为window)。

相关问题