假设我有分散在项目中的window.open (没有name参数),我想要更改实现,以便在没有指定name的地方指定一个默认名称。
我想要做的是将我自己的方法挂接到window.open,这样每当window.open运行时,它就会在内部调用我自己的方法,然后调用window.open (使用name参数)。
这可以通过Javascript实现吗?这样会不会有循环依赖的问题,比如window.open调用我的自定义函数,然后再调用window.open函数呢?
附注:简单地说,我想要做的就是覆盖window.open功能。
发布于 2012-02-07 15:35:34
为了避免循环调用,您需要将原始的window.open函数隐藏在一个变量中。
一种很好的方法(不会污染全局名称空间)是使用闭包。将原始window.open函数作为参数(下面称为open )传递给匿名函数。这个匿名函数是钩子函数的工厂。您的钩子函数通过open参数永久绑定到原始window.open函数:
window.open = function (open) {
return function (url, name, features) {
// set name if missing here
name = name || "default_window_name";
return open.call(window, url, name, features);
};
}(window.open);发布于 2013-08-01 06:35:29
我知道这个回复有点晚,但我觉得一个更通用的解决方案可能对其他人有帮助(尝试覆盖其他方法)
function wrap(object, method, wrapper){
var fn = object[method];
return object[method] = function(){
return wrapper.apply(this, [fn.bind(this)].concat(
Array.prototype.slice.call(arguments)));
};
};
//You may want to 'unwrap' the method later
//(setting the method back to the original)
function unwrap(object, method, orginalFn){
object[method] = orginalFn;
};
//Any globally scoped function is considered a 'method' of the window object
//(If you are in the browser)
wrap(window, "open", function(orginalFn){
var originalParams = Array.prototype.slice.call(arguments, 1);
console.log('open is being overridden');
//Perform some logic
//Call the original window.open with the original params
orginalFn.apply(undefined, originalParams);
});发布于 2012-02-07 15:38:28
P.s.简单地说,我想要做的就是覆盖window.open功能。
var orgOpen = window.open;
window.open = function (...args) {
alert("Overrided!");
return orgOpen(...args);
}
window.open("http://www.stackoverflow.com");https://stackoverflow.com/questions/9172505
复制相似问题