2013-10-30 100 views
0

我試圖爲對象中的每個函數添加一個鉤子,下面是我的代碼,它運行良好。在JavaScript中使用()()將參數傳遞給匿名函數

function foo(){} 
    foo.beforeMethodHook = function(){console.log('Hook was called.');} 
    foo.getInstance = function(){ 
     var newInstance = new foo; 
     var funcNames = Object.getOwnPropertyNames(foo); 
     for(i in funcNames){ 
      var funcName = funcNames[i]; 
      if(funcName == 'getInstance' || funcName == 'beforeMethodHook' || Object.hasOwnProperty(funcName)) continue; 
      newInstance[funcName] = function(){ 
       foo.beforeMethodHook(); 
       return foo[this].apply(foo,arguments); 
      }.bind(funcName); 
     } 
     return newInstance; 
    } 
    foo.test1 = function(arg1){console.log('test1 was called. arg1 = ' + arg1);return true;} 
    foo.test2 = function(arg1,arg2){console.log('test2 was called. arg1 = ' + arg1 + ' , arg2 = ' + arg2);return true;} 
    //Test 
    var f = foo.getInstance(); 
    f.test1('ahaha'); 
    f.test2('heihei','houhou'); 

作爲IE10-不支持功能(){}。綁定(),我試圖.bind()改變爲下面

newInstance[funcName] = (function(){ 
     foo.beforeMethodHook();console.log(arguments); 
     return foo[funcName].apply(foo,arguments); 
    })(funcName); 
(函數(){})()

但問題來了,我失去了參數 f.test1('ahaha')已通過。參數數組只給出[「test1」],這是函數名稱。

我該如何解決這個問題?提前致謝。

+0

見http://stackoverflow.com/questions/3120017/javascript-forwarding-function-calls-that-take-variable-number-of-arguments – Kos

+0

@Kos可能不完全一樣 –

回答

1

您可以實施自己的bind。簡易版:

if (!Function.prototype.bind) { 
    Function.prototype.bind = function(that) { 
     var fn = this; 
     return function() { 
      fn.apply(that, arguments); 
     } 
    }; 
} 

或正確的版本:

if (!Function.prototype.bind) { 
    Function.prototype.bind = function (oThis) { 
    if (typeof this !== "function") { 
     // closest thing possible to the ECMAScript 5 internal IsCallable function 
     throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); 
    } 

    var aArgs = Array.prototype.slice.call(arguments, 1), 
     fToBind = this, 
     fNOP = function() {}, 
     fBound = function() { 
      return fToBind.apply(this instanceof fNOP && oThis 
           ? this 
           : oThis, 
           aArgs.concat(Array.prototype.slice.call(arguments))); 
     }; 

    fNOP.prototype = this.prototype; 
    fBound.prototype = new fNOP(); 

    return fBound; 
    }; 
} 

代碼摘自:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

+0

很酷。有興趣編寫自己的綁定。非常感謝。 –

0

你應該做這樣的事情

newInstance[funcName] = (function(){ 
     console.log(arguments); 
     return function(){ 
      foo.beforeMethodHook(); 
      foo[funcName].apply(foo,arguments); 
     } 
    })(funcName); 
+0

不工作。所有的方法都會被定義的最後一個方法覆蓋,在這種情況下是「test2」。 「test1」不再存在.. –

相關問題