Search code examples
javascriptproxyecmascript-6ecmascript-harmonyes6-proxy

ES6: harmony-proxies: Why does `tracedObj.squared(9)` return undefined?


Why does tracedObj.squared(9) return undefined?

This likely has something to do with the scope of obj being in the wrong scope for it's this call in squared after it calls a method on it's own object.

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);

Output

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

I'm using node v4.4.3 (is it too soon to use these?)

Run the Code

I have to run the command like this:

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


Solution

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

    is missing

    return result;