原型与Undercore冲突



编辑:

我之所以把这个放在首位,是因为我终于解决了实际问题。

Prototypejs添加了一个Array.reduce函数,该函数与下划线集成(请参见:https://github.com/documentcloud/underscore/issues/7)

除了"use prototype>1.6.1),这里似乎没有任何结论,但不幸的是,我无法控制使用了什么原型。除了将_.reduce方法更改为不使用本机函数或代理任何使用reduce的方法(见评论),我看不到任何好的方法来解决这个问题。


我遇到了一个问题,Prototypej与我使用下划线的javascript"应用程序"包含在同一个页面上。

似乎每当我尝试使用函数_.unique时,它实际上是在调用原型函数,这是在一个闭包中,我使用requirejs加载_。当我更改包含库的顺序,使我的应用程序在原型之前包含时,一切都很好,不幸的是,我不能将其用作解决方案,因为我无法控制如何将其包含在任何页面中。

我想知道以前是否有人遇到过这个问题,并有一个可能的解决方案,其中_.unique将始终调用下划线函数,而不是任何称为unique的全局原型函数。

感谢

编辑:

事实上,我认为我可能对被重写的唯一方法是错误的。我刚刚在下划线函数中添加了一些控制台日志,它似乎正在被调用,但返回为空:

_.uniq = _.unique = function(array, isSorted, iterator) {
      console.log("called this");
      console.log(array);
    var initial = iterator ? _.map(array, iterator) : array;
    var results = [];
    // The `isSorted` flag is irrelevant if the array only contains two elements.
    if (array.length < 3) isSorted = true;
    _.reduce(initial, function (memo, value, index) {
        console.log("it never gets here");
      if (isSorted ? _.last(memo) !== value || !memo.length : !_.include(memo, value)) {
        memo.push(value);
        results.push(array[index]);
      }
      return memo;
    }, []);
      console.log(results);
    return results;
  };

第一个控制台日志显示"[1,2,1]",而第二个控制台日志则显示"[]"。这似乎只有当原型包含在页面上时才会发生,所以它发生了一些事情

我添加了另一个日志(它永远不会出现在这里),它一直在执行。看起来underline正在执行"原生"reduce方法,该方法由Prototypejs提供,不使用迭代器。

是的,Prototype.js覆盖reduce,这真是个坏主意。如果reduce是Prototype.js唯一搞砸的东西,那么在_.uniq开始时将Array.prototype.reduce设置为null怎么样?似乎_.intersection_.union都依赖于_.uniq

 _.uniq = _.unique = function(array, isSorted, iterator) {
     var keepIt = Array.prototype.reduce;
     Array.prototype.reduce = null;
     //....
     Array.prototype.reduce = keepIt;
 };

最新更新