-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdecorator.js
96 lines (88 loc) · 2.1 KB
/
decorator.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// import("./utils.mjs").then(val => console.log("val", val));
function Annotation(templateData) {
var s = templateData.raw[0];
console.log("".padStart(4, "=") + s + "".padEnd(4, "="));
}
Annotation`用来装饰整个类`
@testable
class MyTestableClass { }
function testable(target) {
target.isTestable = true;
}
console.log(MyTestableClass.isTestable);
Annotation`用来接收多个参数`
function testableMuti(isTestable) {
return function (target) {
target.isTestable = isTestable;
}
}
@testableMuti(true)
class MyTestableMutiClass { }
console.log(MyTestableMutiClass.isTestable);
Annotation`为类的原型添加方法`
function minxins(...list) {
return function (target) {
Object.assign(target.prototype, ...list);
}
}
const Foo = {
foo() { console.log('foo') }
}
@minxins(Foo)
class MyClass { }
let obj = new MyClass();
obj.foo();
Annotation`方法的装饰`
class Person {
@readonly
name() { return `${this.first} ${this.last}` }
}
function readonly(target, name, descriptor) {
descriptor.writable = false;
return descriptor;
}
var person = new Person();
try {
person.name = "123";
} catch (err) {
console.error(err.message);
}
Annotation`不可遍历`
class Person2 {
@nonenumerable
get kidCount() { return 2; }
}
function nonenumerable(target, name, descriptor) {
descriptor.enumerable = false;
return descriptor;
}
var person = new Person2();
console.log(person.kidCount, Reflect.ownKeys(person))
Annotation`输出日志`
class Math {
@log
add(a, b) {
return a + b;
}
}
function log(target, name, descriptor) {
var oldValue = descriptor.value;
descriptor.value = function () {
console.log(`Calling ${name} with`, arguments);
return oldValue.apply(this, arguments);
};
return descriptor;
}
const math = new Math();
math.add(2, 4);
Annotation`混入类`
class MyBaseClass { }
let MyMixin = (superclass) => class extends superclass {
foo() {
console.log('foo from MyMixin');
}
};
class MyClass2 extends MyMixin(MyBaseClass) {
}
var myClass = new MyClass2();
myClass.foo();