【问题标题】:ES6: harmony-proxies: Why does `tracedObj.squared(9)` return undefined?ES6:和谐代理:为什么 `tracedObj.squared(9)` 返回未定义?
【发布时间】:2016-10-17 00:31:55
【问题描述】:

为什么tracedObj.squared(9) 返回未定义?

这可能与 obj 的范围在错误的范围内有关,因为它在 squared 中调用了 this 在它自己的对象上调用了一个方法之后。

代码

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

输出

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

我正在使用 node v4.4.3(现在使用这些是否为时过早?)

运行代码

我必须像这样运行命令:

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

【问题讨论】:

标签: javascript proxy ecmascript-6 ecmascript-harmony es6-proxy


【解决方案1】:
return function(...args) {
    let result = origMethod.apply(this, args);
    console.log(propKey + JSON.stringify(args) + ' -> ' + JSON.stringify(result));
};

不见了

return result;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-11
    • 2014-10-24
    • 2021-12-11
    • 2019-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多