【发布时间】: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
【问题讨论】:
-
在这里找到了代码:2ality.com/2015/10/intercepting-method-calls.html 但我相信作者使用的是FF。
-
你从来没有在你的替换函数中
return result;? -
@loganfsmyth 就是这样。
标签: javascript proxy ecmascript-6 ecmascript-harmony es6-proxy