从数组实例中隐藏额外的方法

Hide extra methods from array instances

本文关键字:方法 隐藏 数组 实例      更新时间:2023-09-26

我创建了一个数组,其中包含所有变化方法的事件。如果你做。push。on('push')被触发。我通过向数组实例添加一个新的push来实现这一点。现在的问题是,如果您在console.log或比较测试中的数组,新方法也会显示出来。有办法隐藏这些新方法吗?

代码:

var oar = function (base) {
    var arr = base || [];
    var handlers = {};
    arr.on = function (event, callback) {
        if (typeof handlers[event] === 'undefined') {
            handlers[event] = [];
        }
        handlers[event].push(callback);
    };
    var proxy = function (method) {
        var args = Array.prototype.slice.call(arguments, 1);
        var result = Array.prototype[method].apply(arr, args);
        process.nextTick(function () {
            if (typeof handlers[method] !== 'undefined') {
                handlers[method].forEach(function (handler) {
                    handler(arr);
                });
            }
        });
        return result;
    };
    [ 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift' ].forEach(function (method) {
        arr[method] = proxy.bind(null, method);
    });
    return arr;
};
module.exports = oar;

如果您console.log数组或例如使用should (a.should.eql(…))在测试中验证它,它会考虑所有代理方法加上on方法。

 [ 
    'one',
    'two',
    on: [Function],
    pop: [Function],
    push: [Function],
    reverse: [Function],
    shift: [Function],
    sort: [Function],
    splice: [Function],
    unshift: [Function] 
]

如果我理解正确的话,我可以代理原型代替,但然后数组的所有实例将有这些新方法。

您想要的是使用Object.defineProperty设置这些属性,它将它们默认设置为不可枚举的:

Object.defineProperty(arr, method, {value: proxy.bind(null, method)});