在网页中的Javascript特效,一般是由好多函数组成.但这样的特效,在使用中,会有诸多不便.但如果封装,一般会卡在"如何使HTML元素的事件,使用我们封装类的成员函数作为处理函数" 那么,如何解决这个问题呢? 只要切换事件全局上下文为我们类实例的上下文就可以了. 如何实现切换呢? 可以用javascript的委托,感觉原理就像把成员函数的二次寻址,转化成用一个自定义函数来实现寻址和参数传递. 代码实现如下: // ajax .net 一段代码 Function.createDelegate = function(instance, method) { return function() { method.apply(instance, arguments); } } 有了上面的生成委托代码的函数,我们可以这样来设置事件 function AdShower(uiImg) { this.uiImg = uiImg; } AdShower.prototyp.init = function() { this.uiImg.onmousemove = Function.createDelegate(this,this.onmousemove); } AdShower.prototyp.onmousemove = function() { alert(this.uiImg.outerHTML); }
这时,通过createDelegate,我们成功的完成了切换
|