2016-06-15 21 views
0

Warum gibt tracedObj.squared(9) zurück undefined?ES6: Harmony-Proxies: Warum kehrt `tracedObj.squared (9)` undefined zurück?

Das hat wahrscheinlich etwas mit dem Umfang von obj im falschen Umfang ist zu tun, denn es ist this Anruf in squared, nachdem sie ein Verfahren auf seinen eigenes Objekt aufruft.

-Code

"use strict"; 
var Proxy = require('harmony-proxy'); 

function traceMethodCalls(obj) { 
    let handler = { 
     get(target, propKey, receiver) { 
      const origMethod = target[propKey]; 
      return function(...args) { 
       let result = origMethod.apply(this, args); 
       console.log(propKey + JSON.stringify(args) + ' -> ' + JSON.stringify(result)); 
      }; 
     } 
    }; 
    return new Proxy(obj, handler); 
} 

let obj = { 

    multiply(x, y) { 
     return x * y; 
    }, 
    squared(x) { 
     return this.multiply(x, x); 
    } 
}; 

let tracedObj = traceMethodCalls(obj); 
tracedObj.multiply(2,7); 

tracedObj.squared(9); 
obj.squared(9); 

Ausgabe

multiply[2,7] -> 14 
multiply[9,9] -> 81 
squared[9] -> undefined 
undefined 

Ich verwende Knoten v4.4.3 (ist es noch zu früh diese zu verwenden?)

Führen Sie den Code

I muss den Befehl wie folgt ausführen:

node --harmony-proxies --harmony ./AOPTest.js

+0

den Code gefunden für diese hier: http://www.2ality.com/2015/10/intercepting-method-calls.html aber ich glaube, den Autor benutzt FF. – leeand00

+1

Sie 'nie zurückgeben' 'in Ihrer Ersatzfunktion? – loganfsmyth

+0

@loganfsmyth das war es. – leeand00

Antwort

1
return function(...args) { 
    let result = origMethod.apply(this, args); 
    console.log(propKey + JSON.stringify(args) + ' -> ' + JSON.stringify(result)); 
}; 

fehlt

return result;