1. 程式人生 > 其它 >JS TS 裝飾器

JS TS 裝飾器

裝飾器

2021.07.07:
    今天面試的時候一時間沒想起來,現在回想一下,這相當時`擴充套件作用域`,可以修改接下來的函式

裝飾器是可以修改其他函式功能的函式,寫法 @ + 函式名 在 Python 隨處可見。

早期 TypeScript 在 1.5 版本釋出了對裝飾器的支援,現在 ES6 也通過了裝飾器的提案,目前處於徵集的第二階段

在 Python 中的簡單用法

def my_decorator1(fn):
    print("my decorator1")
    return fn

@my_decorator1
def my_func1():
    print("my function1")

my_func1()
# my decorator1
# my function1

這相當於

def my_decorator2(fn):
    def wrapper():
        print("my decorator2")
        return fn()
    return wrapper

def my_func2():
    print("my function2")

my_func = my_decorator2(my_func2)
my_func()
# my decorator2
# my function2 

在 JS/TS 中簡單使用

裝飾整個類

@testable
class MyTestableClass {
  // ...
}

function testable(target) {
  target.isTestable = true;
}

MyTestableClass.isTestable // true