新手到javascript中的类并不能解决这个问题。实际上,另一种方法可以返回一个回调构造函数然后我可以从那里调用一个方法,但也许有一个更简单的方法?
function sample() {} //constructor
sample.prototype = {
onemethod: function () {},
anothermethod: function () {
onemethod(); //Doesn't work
this.onemethod(); //Still the same
}
}
答案 0 :(得分:0)
要使其正常工作,您需要正确使用它。需要通过new
调用构造函数。
var s = new sample();
s.anothermethod();
// identical to
sample.anothermethod.apply(s);
这样,this
将代表s
(这是外部背景,通常为window
)。