日期:2014-05-16  浏览次数:20318 次

又是这个问题,怎么追加运行事件......
JScript code

<script>
var A = function ()
{
    this.alert = function ()
    {
        alert('A');
    }
}

var B = function ()
{
    this.alert = function ()
    {
        alert('B');
    }
}
var A = new A();
var B = new B();

A.alert();
</script>




想执行A.alert(); 的时候后接着再执行B.alert();的代码
前提是A函数不能改动。要怎么写呢? 



目前是这么一个情况,
是要做类似插件的功能,能给用户开发插件。
除了绑定的系统函数运行之外,也要让插件开发者的自定义函数执行。
前提是系统的函数都不能改动,也就上面的A函数不能改动。

上一贴坛里一朋友提到用call但最后还是不成功。


------解决方案--------------------
封装一个C,把A跟B都执行了
------解决方案--------------------
用jquery吧
------解决方案--------------------
JScript code

<script>
Aspects = new Object();
Aspects.addBefore = function(obj, fname, before) {
    var oldFunc = obj[fname];
    obj[fname] = function() {
        return oldFunc.apply(this, before(arguments, oldFunc, this));
    };
};
Aspects.addAfter = function(obj, fname, after) {
    var oldFunc = obj[fname];
    obj[fname] = function() {
        return after(oldFunc.apply(this, arguments), arguments, oldFunc, this);
    };
};
Aspects.addAround = function(obj, fname, around) {
    var oldFunc = obj[fname];
    obj[fname] = function() {
        return around(arguments, oldFunc, this);
    };
};



var A = function (){
    this.alert = function (){
        alert('A');
    }
}

var B = function (){
    this.alert = function (){
        alert('B');
    }
}
var a = new A();
var b = new B();

Aspects.addAfter(a,"alert",b.alert);//将b.alert方法动态增加给a

a.alert();


</script>

------解决方案--------------------
楼主找找 js 继承

写一个类,继承A
------解决方案--------------------
方法1

var A=function()
{
B.apply(this,arguments);
this.alert = function ()
{
alert('A');
}
}

var B=function()
{
this.alert = function ()
{
alert('B');
}
}

这种方法缺点是A函数把B函数里的同名方法覆盖了

方法2

var A=function()
{
this.alert = function ()
{
alert('A');
}
}

var B=function()
{
this.alert = function ()
{
alert('B');
}
}
A.prototype=new B();

new A().alert();
A.prototype.alert.apply();


方法3
var A=function()
{
this.alert = function ()
{
alert('A');
}
}

var B=function()
{
this.alert = function ()
{
alert('B');
}
}
function c(){
var a=new A();
var b=new B();
a.alert();
b.alert();
}
var s=new c();
------解决方案--------------------
不必要那样复杂。
JScript code

<script>
Function.prototype.$Asynch = function ( Method ) {
    this ();
    Method ();
}

var A = function ()
{
    this.alert = function ()
    {
        alert('A');
    }
}

var B = function ()
{
    this.alert = function ()
    {
        alert('B');
    }
}

var A = new A();
var B = new B();
A.alert.$Asynch( B.alert )
</script>

------解决方案--------------------
JS继承
------解决方案--------------------
JScript code
            var A = function ()
            {
                this.alert = function ()
                {
                    alert('A');
                }
            }
            var B = function ()
            {
                this.alert = function ()
                {
                    a