2013-06-02 26 views
1

我創建了一個包含所有變異方法的事件的數組。所以如果你做a.push a.on('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數組或實例的使用應(a.should.eql(...)),以驗證它在測試中,它需要在帳戶中的所有代理'方法加on方法。

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

如果我理解正確的是我可以代替原型,但然後所有的數組實例將有這些新的方法。

回答

5

你想要的是使用Object.defineProperty設置這些屬性,它們設置爲無默認枚舉:

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

'enumerable'是'默認FALSE'。 –

+0

@MattBall是的,你說得對,謝謝。 –