1

是否可以覆盖缩小的 Javascript 文件中包含的函数?

详细信息:我正在尝试覆盖 Twitter Bootstrap Typeahead 插件 (v2.3.2) 中的 process() 函数,以便在返回的项目超过显示的项目时在下拉列表底部添加一个指示器。

这是我的代码:

var customProcess = function (items) {
    var that = this

    items = $.grep(items, function (item) {
        return that.matcher(item)
    })

    items = this.sorter(items)

    if (!items.length) {
        return this.shown ? this.hide() : this
    }

    //Get the default item slice and determine whether the indicator is needed
    var itemSlice = items.slice(0, this.options.items);
    if (items.length > this.options.items) {
        itemSlice.push("...");
    }

    return this.render(itemSlice).show();
};

// Reassign the typeahead.process() function to the customized
// version that adds a visual indicator if more items are 
// returned than the amount shown (options.items).
$.fn.typeahead.Constructor.prototype.process = customProcess;

如果我使用的是 Bootstrap JavaScript (bootstrap.min.js) 的缩小版本,这将失败并且实际上完全杀死了 typeahead 功能。如果我改为获取非缩小版本(bootstrap.js),它会完美运行。

[作为旁注,我之前在较早版本的 typeahead 插件(我相信是 v1.8.x)上使用了相同的方法,并且它也与最小化版本完美配合。我是不是走运了?】

4

1 回答 1

1

Minification does not change the "visible" API. If you can call a function as library.functionName(...) on the minified library, then you can override that property and turn it into something else (note that a function is just a property called with the execution operator () added to it).

With one caveat: if that function was set up using Object.defineProperty, with either default configurable and/or writable configuration options (or these values explicitly set to false), then it will be "locked" from being modified (it will not be deletable and/or assignable, respectively).

于 2013-06-21T03:17:07.240 回答