在重绑定函数引用时避免递归
Avoid recursion in rebinding function reference
库X
多次试图调用其方法foo
,从而严重损害了我的插件Y
的用户体验。我的插件Y
引入了任意逻辑shouldFooExecute
,必须在X.foo
的最终结果发生之前考虑。然而,当用户通过Y
的旅程(发生在一个模态窗口中)完成时,X
应该能够继续,好像什么都没有发生。
// This is an external library. I can't modify and shouldn't overwrite it.
x = {
// A method that completely screws my plugin
foo: function(){
/* nasty stuff */
}
}
// This is my widget!
y = {
// Init function, called when my plugin boots
init: function(){
// This scope handles the x.foo problem
void function rebindFoo(){
// Internal state
var shouldFooExecute = false;
// I need to be able to refer back to the original foo after I've temporarily rebound it
var x_foo = x.foo;
// Re-attach foo to its original definition & context
function rebindFooToX(){
// ECMAScript 5 browsers are fine!
if(Function.prototype.bind){
// x.foo is literally rebound to pretty much exactly what it was
x.foo = x_foo.bind(x);
}
// Others not so good when this function executes a second time
else {
x.foo = function rebound_foo(){
// An extra scope! Horrible. And it's recursive!
return x_foo.apply(x, arguments);
}
}
}
x.foo = function y_foo(){
// Stop and consider y's esoteric logic
if(shouldFooExecute){
// If it's fine, we rebind everything
rebindFooToX();
// This will have the intended effect
x.foo();
}
}
}
}
}
当我的插件在不支持bind的浏览器上重新初始化时,问题就出现了。x.foo
最终引用rebound_foo
,这是循环的。我可以编写任何类型的逻辑来避免递归,并在存在的情况下使用现有的rebound_foo
?
您可以使用https://github.com/kriskowal/es5-shim将Function.prototype.bind
方法添加到本地不支持它的浏览器
这是7个月后的事实,所以这个问题可能是OBE,但我想指出,这取决于X是如何定义的,你可以尝试继承:
var x = function() {
this.foo = function() {
console.log("from x");
};
this.bar = function() {
console.log("from x");
};
}
var y = function() {
this.foo = function() {
console.log("from y");
}
}
y.prototype = new x();
var test = new y();
test.foo(); // will output: from y
test.bar(); // will output: from x
相关文章:
- 数组在递归方法中设置为null
- Kendo:我该如何在树视图中创建一个递归的hieiarchy
- 递归使用 eval() 是检查程序执行的好方法吗?
- 使用递归、Ramda.js和无点样式重构字符串的getPermutations()
- 递归深度比较
- Eloquent JavaScript递归示例如何终止为返回1,但仍然输出指数值
- 递归函数中断
- 如何递归地获取嵌套对象中所有子对象的列表
- JavaScript 素数搜索无限递归
- 在递归生成器函数中,yield后面的*(星号/星号)语法意味着什么
- 递归|两个函数名
- 有没有一种方法可以在Javascript中进行可变递归currying
- 如何对不同的表递归使用以下代码
- 将jQuery对象传递到setTimeout递归函数中
- Javascript递归函数引用了这一点
- 在递归调用中避免空引用
- 如何在递归调用中保持对数据结构的引用
- 猫鼬递归查询父引用
- 在重绑定函数引用时避免递归
- 在递归函数中保持对象引用