当我在网站上使用JS时,我经常喜欢使用function()将代码拆分为逻辑完整的模块,通常是这样的:
function BigClass() {
this.doOneThing = function() {
}
this.doAnother = function() {
}
}
后来我使用jQuery的.ready()来创建我正在使用的类的实例,并将它们挂在各种事件上。
var bigClassInstance = new BigClass();
$('a.something').click(bigClassInstance.doOneThing);
我的问题是......从我对 doOneThing()的调用中执行 doAnotherThing()函数的最佳方法是什么?在较小的项目上工作,我只会使用 bigClassInstance.doAnotherThing(); ,但这不是可移植的。
这样做的正确方法是什么?
答案 0 :(得分:1)
不确定我是否理解该问题,但是通过使用proxy函数,您可以更改单击处理程序调用的函数的上下文,即make this
引用您的bigClassInstance
和不是jQuery点击上下文:
function BigClass() {
this.doOneThing = function() {
this.doAnother();
}
this.doAnother = function() {
}
}
$('a.something').on( "click", $.proxy( bigClassInstance.doOneThing, bigClassInstance ) );