Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
U
umi-test-demo
Project
Project
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
梁柱
umi-test-demo
Commits
f401796e
Commit
f401796e
authored
Apr 27, 2023
by
梁柱
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
装饰器使用
parent
ef863b46
Show whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
86 additions
and
0 deletions
+86
-0
.gitignore
.gitignore
+1
-0
demo2.ts
src/util/demo2.ts
+85
-0
No files found.
.gitignore
View file @
f401796e
...
@@ -18,3 +18,4 @@
...
@@ -18,3 +18,4 @@
/src/.umi-production
/src/.umi-production
/src/.umi-test
/src/.umi-test
/.env.local
/.env.local
.idea
src/util/demo2.ts
0 → 100644
View file @
f401796e
// 1. 类装饰器 装饰器应用于类的构造函数,可用于观察、修改或替换类定义。
interface
Person
{
name
:
string
;
age
:
string
;
}
function
enhancer
(
target
:
any
):
void
{
target
.
name
=
'persion'
;
target
.
prototype
.
name
=
'lison'
;
target
.
prototype
.
age
=
18
;
}
// 1.1 普通装饰器
@
enhancer
class
Person
{
constructor
()
{}
}
const
p
:
Person
=
new
Person
();
// console.log(p.name);
// console.log(p.age);
// 1.2 装饰器工厂
function
enhancer2
(
name
:
string
,
age
:
number
)
{
return
function
(
target
:
any
):
void
{
target
.
prototype
.
name
=
name
;
target
.
prototype
.
age
=
age
;
};
}
@
enhancer2
(
'lison'
,
18
)
class
Person2
{
constructor
()
{}
}
const
p2
:
Person
=
new
Person
();
// console.log(p2.name);
// console.log(p2.age);
// 2. 属性装饰器
// 属性装饰器用来装饰属性
// 属性装饰器表达式会在运行时当做函数被调用,传入下列两个参数
// 第一个参数: 对于静态成员来说是类的构造函数,对于实例成员是类的原型对象
// 第二个参数: 是属性的名称
// 属性装饰器在属性声明之前声明,返回值会被忽略。
const
LowerDecorator
:
PropertyDecorator
=
(
target
:
Object
,
propertyKey
:
string
|
symbol
,
):
void
=>
{
let
value
:
string
;
console
.
log
(
target
,
propertyKey
);
Object
.
defineProperty
(
target
,
propertyKey
,
{
get
:
()
=>
{
console
.
log
(
value
);
return
value
?.
toLowerCase
();
},
set
:
(
v
)
=>
{
value
=
v
;
},
});
};
class
Hd
{
@
LowerDecorator
title
:
string
|
undefined
;
constructor
()
{
this
.
title
=
'BBa'
;
}
}
const
obj
=
new
Hd
();
// console.log(obj.title) // bleak
// Object.defineProperty(obj, 'title', {
// get: () => {
// console.log(value)
// return value?.toLowerCase()
// },
// set: v => {
// value = v
// }
// });
// obj.title = 'Bleak'
console
.
log
(
obj
.
title
);
// bleak);
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment