1

X反复尝试调用它的方法foo来严重损害我的插件Y的用户体验。我的插件引入了在最终结果发生之前必须考虑的Y任意逻辑。然而,当用户旅程(发生在模态窗口中)完成时,应该能够继续进行,就好像什么都没发生一样。shouldFooExecuteX.fooYX

// 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();
        }
      }
    }
  }
}

当我的插件在不支持绑定的浏览器上重新初始化时,问题就出现了。x.foo最终引用rebound_foo的是循环的。我可以编写任何逻辑来避免递归并在存在rebound_foo的情况下使用现有的逻辑吗?

4

2 回答 2

0

您可以使用https://github.com/kriskowal/es5-shimFunction.prototype.bind方法添加到本机不支持它的浏览器。

于 2013-03-26T13:14:34.297 回答
0

事发后 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
于 2013-10-29T12:24:35.700 回答