Javascript:从同一类的另一个方法访问类方法
问题描述:
新手到JavaScript类,并不能解决这个问题。实际上,另一种方法可以返回一个回调给构造函数,然后我可以从那里调用一个方法,但也许有一个更简单的方法?Javascript:从同一类的另一个方法访问类方法
function sample() {} //constructor
sample.prototype = {
onemethod: function() {},
anothermethod: function() {
onemethod(); //Doesn't work
this.onemethod(); //Still the same
}
}
答
对于它的工作,你需要正确使用它。构造函数需要通过new
调用。
var s = new sample();
s.anothermethod();
// identical to
sample.anothermethod.apply(s);
这样,this
将代表s
(这外上下文中,通常window
)。
'this.onemethod()'起作用。另外,在提问时,请创建一个自包含的完整示例,包括如何创建和调用方法。 –
'this.onemethod()'正在'alert/console.log'内使用方法'onemethod' –
研究javascript原型 – Dom