-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdecorate.js
More file actions
36 lines (28 loc) · 800 Bytes
/
decorate.js
File metadata and controls
36 lines (28 loc) · 800 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
/*
* 装饰者模式
* */
"use strict";
function decorate(component) {
const proto = Object.getPrototypeOf(component);
function Decorator(component) {
this.component = component;
}
Decorator.prototype = Object.create(proto);
//new method
Decorator.prototype.greetings = function () {
return 'Hi!';
};
//delegated method
Decorator.prototype.hello = function () {
return this.component.hello.apply(this.component, arguments);
};
return new Decorator(component);
}
class Greeter {
hello(subject) {
return `Hello ${subject}`;
}
}
const decoratedGreeter = decorate(new Greeter());
console.log(decoratedGreeter.hello('world')); // uses original method
console.log(decoratedGreeter.greetings()); // uses new method