Kev*_*Kev 155 javascript overriding user-defined-functions
我有一个函数,a()我想要覆盖,但也有原始a()的顺序执行,具体取决于上下文.例如,有时当我生成页面时,我想要覆盖如下:
function a() {
new_code();
original_a();
}
Run Code Online (Sandbox Code Playgroud)
有时像这样:
function a() {
original_a();
other_new_code();
}
Run Code Online (Sandbox Code Playgroud)
我如何original_a()在超越范围内获得这一点a()?它甚至可能吗?
请不要以这种方式建议替代方法,我知道很多.我特意问这个问题.
Mat*_*ley 177
你可以这样做:
var a = (function() {
var original_a = a;
if (condition) {
return function() {
new_code();
original_a();
}
} else {
return function() {
original_a();
other_new_code();
}
}
})();
Run Code Online (Sandbox Code Playgroud)
original_a在匿名函数内部声明可以防止它混乱全局命名空间,但它可以在内部函数中使用.
像评论中提到的Nerdmaster一样,请务必()在最后添加.您想调用外部函数并将结果(两个内部函数之一)a存储在其中,而不是存储外部函数本身a.
Phi*_*Hoy 85
该代理模式可以帮助你:
(function() {
// log all calls to setArray
var proxied = jQuery.fn.setArray;
jQuery.fn.setArray = function() {
console.log( this, arguments );
return proxied.apply( this, arguments );
};
})();
Run Code Online (Sandbox Code Playgroud)
上面将其代码包装在一个隐藏"代理"变量的函数中.它将jQuery的setArray方法保存在一个闭包中并覆盖它.然后,代理会记录对方法的所有调用,并将调用委托给原始调用.使用apply(this,arguments)可以保证调用者无法注意到原始方法和代理方法之间的区别.
Nar*_*h S 27
谢谢大家代理模式真的有帮助.....实际上我想调用一个全局函数foo ..在某些页面我需要做一些检查.所以我做了以下几点.
//Saving the original func
var org_foo = window.foo;
//Assigning proxy fucnc
window.foo = function(args){
//Performing checks
if(checkCondition(args)){
//Calling original funcs
org_foo(args);
}
};
Run Code Online (Sandbox Code Playgroud)
Thnx这对我有帮助
小智 10
您可以使用如下构造覆盖函数:
function override(f, g) {
return function() {
return g(f);
};
}
Run Code Online (Sandbox Code Playgroud)
例如:
a = override(a, function(original_a) {
if (condition) { new_code(); original_a(); }
else { original_a(); other_new_code(); }
});
Run Code Online (Sandbox Code Playgroud)
编辑:修正了一个错字.
| 归档时间: |
|
| 查看次数: |
193986 次 |
| 最近记录: |