-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy pathaspect.js
More file actions
55 lines (45 loc) · 970 Bytes
/
aspect.js
File metadata and controls
55 lines (45 loc) · 970 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict';
class Point {
#x;
#y;
constructor(x, y) {
this.#x = x;
this.#y = y;
}
move(dx, dy) {
this.#x += dx;
this.#y += dy;
}
clone() {
return new Point(this.#x, this.#y);
}
toString() {
return `(${this.#x}, ${this.#y})`;
}
}
const aspect = (target, methodName, { before, after }) => {
const method = target[methodName];
target[methodName] = function (...args) {
before?.apply(this, args);
const result = method.apply(this, args);
after?.call(this, result, ...args);
return result;
};
};
aspect(Point.prototype, 'move', {
before(dx, dy) {
console.log(`Before move: ${this.toString()} moving by (${dx},${dy})`);
},
after() {
console.log(`After move: ${this.toString()}`);
},
});
aspect(Point.prototype, 'clone', {
after(result) {
console.log(`After clone: ${result.toString()}`);
},
});
// Usage
const p1 = new Point(10, 20);
const c1 = p1.clone();
c1.move(-5, 10);