The Advice Patternは、JavaScriptなどのような動的言語では本当に簡単です:
function before(behavior) {
return method => function beforeHandler(...args) {
behavior.apply(this, args);
return method.apply(this, args);
};
}
function after(behavior) {
return method => function afterHandler(...args) {
const result = method.apply(this, args);
behavior.apply(this, [args, result]);
return result;
};
}
const id = _ => _;
function withAdvice({before: beforeBehavior = id, after: afterBehavior = id, skip: [] }) {
return Class => Object.keys(Class.prototype).forEach(methodName => {
if (!skip.contains(methodName)) {
const method = Class.prototype[methodName];
const afterDecorator = after(afterBehavior);
const beforeDecorator = before(beforeBehavior);
Class.prototype[methodName] = afterDecorator(beforeDecorator(method));
}
});
}
@withAdvice({
after() {
this.calcRank();
},
skip: ['calcRank']
})
class Item {
addUser() {}
removeUser() {}
addGroup() {}
removeGroup() {}
addUnit() {}
removeUnit() {}
calcRank() {}
}
は素晴らしい見えます!私が行って 'TypeScript'で試してみると、セットアップは違うでしょうか?この行について説明してください: 'const id = _ => _;'ありがとう。 – user1692261