2017-02-03 2 views

答えて

1

ためのオブジェクト

var phas = new Proxy({b:9, 
      cont:0, 
      statistic:function(){ 
       console.log(this.cont) 
       this.cont++ 
       } 
      }, { 
       has: function (target, key) { 
        if (key == "a") return false; 
        return true; 
       }, 


       apply: function() { 
        console.log('run call ') 
       } 
      } 
    ) 

phas.run(); 

Uncaught TypeError: phas.run is not a function

マニュアルのinitializeメソッドのgetterを持っていると思います。

プロキシを作成するときに、そのオブジェクトにプロキシを作成します。プロキシは自動的にオブジェクトのプロパティに拡張されません。

applyトラップは関数にのみ適用でき、関数をプロキシして呼び出すと、期待通りに機能します。

あなたが動的にメソッドを作成したい場合は、代わりにこのような何かをする必要があります。

var p = new Proxy({}, { 
    get: function(target, prop) { 
     // If the property exists, just return it 
     if (prop in target) 
      return target[prop]; 
     // Otherwise, return a function 
     return function() { console.log("Some method", prop); }; 
    } 
}); 

p.run() //Logs: Some method run 
typeof p.a == 'function' // true