我正在编写一些JavaScript分析位,需要能够拦截闭包内的方法。
我设法让这个工作:
var t = (function() {
var echo = function(v) { console.log("calling echo with " + v); };
return {
intercept: function(n, f) {
var old = eval(n);
var newFunction = (function(that, old){
return f(that, old);
})(this, old);
eval(n + " = newFunction ");
},
getEchoFunction: function() { return echo; }
};
})();
var c = t.getEchoFunction();
c("hello");
t.intercept("echo", function(that,old){
return function() {
console.log("before echo");
old.apply(that,arguments);
console.log("after echo");
};
});
c = t.getEchoFunction();
c("world");
输出是:
"calling echo with hello" "before echo" "calling echo with world" "after echo"
因此,这个“拦截”API让我拦截并重写隐藏在闭包中的函数声明。
然而,世界上有很多关于评估的抱怨。
有没有办法编写相同的API而无需在eval
函数中使用intercept
?
答案 0 :(得分:3)
不,遗憾的是,无法访问与window[...]
工作方式类似的非全局范围。
但是,根据您使用对象而不是原生作用域需要做什么,这将是一个好主意。