typescript js裝飾器與ts裝飾器梳理

2021-10-09 10:34:20 字數 3165 閱讀 9401

js裝飾器曾經有巨大改版,主要是在2個方面:

第乙個方面是多個裝飾器在裝飾類的原型方法時,執行順序不同:

function

dec(id)

class

example

}

evaluated 2

evaluated 1

executed 2

executed 1

evaluated 1

evaluated 2

executed 2

executed 1

function

dec(target, prop, descriptor)

= descriptor;

delete descriptor.initializer;

delete descriptor.writable;

descriptor.

get=

function()

;}class

example

//當裝飾器作為修飾類的時候,會把構造器傳遞進去

function

addnameeat

(constructor

:typeof person);}

@addnameeat

class

person

}let p: person =

newperson()

;console

.log

(p.name);p.

eat(

);

function

addnameeat

(name:

string);

};}@addnameeat

('yehuozhili'

)class

person

}let p: person =

newperson()

;console

.log

(p.name);p.

eat(

);

inte***ce

personextends

extends

person

function

addnameeat

(name:

string

)hello()

static aaa:

string

="1"

;static bbb:

number

=111;}

;};}

@addnameeat

("yehuozhili"

)class

person

static aaa:

string

="222";}

let p =

newperson()

;console

.log

(p.name)

;//undefiend

p.eat()

;//修改後

p.hello()

;// new function yehuozhili

let k =

person

console

.log

(person.aaa)

;//'1'

console

.log

(k.bbb)

//111

function

addnameeat

(name:

string);

}@addnameeat

('yehuozhili'

)class

person

}let p: person =

newperson()

;console

.log

(p.name);p.

eat(

);

function

uppercase

(target:

any, propertykey:

string);

// 用來替換的setter

const

setter

=function

(newval:

string);

// 替換屬性,先刪除原先的屬性,再重新定義屬性if(

delete target[propertykey]))

;}}

@test

public

static age:

number=10

;

function

noenumerable

( target:

any,

_property:

string

, descriptor: propertydescriptor

)class

person

@noenumerable

getname()

@tonumber

sum(...args:

any)

}

@test

static

getaa()

inte***ce

person

function

addage

(target:

any, methodname:

string

, paramsindex:

number

)class

person

static

aaa(@addage a:

string)}

let p =

newperson()

;p.login

('yehuozhili'

,'123456'

)

裝飾器之類裝飾器

外部的方法至今都玩過了,現在來思索一下的方法這麼裝飾 類方法修飾器 類的方法唯一的特殊點在於,self內部是可以呼叫的,但是在外部卻是隱藏的,那這個怎麼搞 為求穩妥,先定參修飾乙個 def godme fun def godme self,message print before fun self,...

python裝飾器 裝飾器

由於函式也是乙個物件,而且函式物件可以被賦值給變數,所以,通過變數也能呼叫該函式。def now print 2015 3 25 f now f 2015 3 25 函式物件有乙個 name 屬性,可以拿到函式的名字 now.name now f.name now 現在,假設我們要增強now 函式的...

python裝飾器 函式裝飾器,類裝飾器

只要實現此 模式,這個obj就叫乙個裝飾器 參考 函式裝飾器 例子 def decorator func def inner args,kwargs print before.res func args,kwargs print after.return res return inner decor...