es6超好用的語法糖Decorator

2021-10-23 01:43:19 字數 2710 閱讀 5675

decorator(修飾器/裝飾器)是es6提出的語法糖,用於修改類的行為。不過目前主流瀏覽器都沒有很好的支援,我們需要用babel來轉換為瀏覽器能識別的語言。在這篇文章中將介紹decorator的基礎用法和一些應用例項。

@testable

class myclass{}

function testable(target)

console.log(myclass.istestable) // true

貼一下babel轉換後的**,

var _class;

let myclass = testable(_class = class myclass {}) || _class;

function testable(target)

也可以在prototype上修改屬性,也可以為修飾器新增多個引數。

@testable(false)

class myanotherclass

function testable(status)

}console.log('myclass.istestable',myanotherclass.prototype.istestable) // false

當然我們通過修飾器,把某個物件的方法新增到目標類的例項上,注意要在類的prototype上新增。

const foo=

function testable(...list)

}@testable(foo)

class myanotherclass{}

const obj=new myanotherclass()

console.log('myclass.istestable',obj.istestable) // true

class myreactcomponent extends react.component {}

export default connect(mapstatetoprops, mapdispatchtoprops)(myreactcomponent);

如果使用decorator,**可讀性更高了一些。

@connect(mapstatetoprops, mapdispatchtoprops)

export default class myreactcomponent extends react.component {}

// target:在方法中的target指向類的prototype

function readonly(target,key,descriptor)

class myclass`)}

}

其中descriptor物件為object的資料屬性。之前我們會使用object.defineproperty來描述物件的屬性,如下:

var person = {}

object.defineproperty(person,'name',);

對應到descriptor為下面四個屬性:

;
我們開始寫乙個@log修飾器,可以輸出日誌:

class math

}const math=new math()

math.add(1,2)

function log(target,name,descriptor) with $`)

}return descriptor

}

上面的**中,@log作用是在返回結果前,列印函式名和其引數,起到輸出日至的作用。上面的程式執行後,控制台將輸出:

calling add with
良好命名的修飾器可以起到簡潔注釋的作用,如下:

class example 

}

多個修飾器的執行順序是由外向內進入;再由內向外執行。

class example 

}function decorator(id)

控制台輸出

id is  1

id is 2

executed 2

executed 1

babel外掛程式transform-decorators還沒有正式版,我們可以用transform-decorators-legacy

yarn add babel-plugin-transform-decorators-legacy babel-preset-es2017
因為我們為了測試,沒必要非得放在瀏覽器裡看了,可以用node執行babel轉換後的檔案。直接執行yarn start

// package.json

"scripts": ,

ecmascript 6 入門 -- 修飾器

ES6中物件簡寫屬性名的語法糖

首先讓我們看一段 let demo1 屬性操作的get方法 function get key 屬性操作的 set方法 function set key,value 將物件還原成乙個空物件的方法 function clear 根據commonjs規範,模組輸出 module.exports 在模組的末...

es6 基本語法

es6規定暫時性死區和let const語句不出現變數提公升,主要是為了減少執行時錯誤,防止在變數宣告前就使用這個變數,從而導致意料之外的行為。這樣的錯誤在 es5 是很常見的,現在有了這種規定,避免此類錯誤就很容易了。總之,暫時性死區的本質就是,只要一進入當前作用域,所要使用的變數就已經存在了,但...

ES6語法總結

1 物件的寫法 es5中物件 es6中物件 注意這種寫法的屬性名稱和值變數是同乙個名稱才可以簡寫,否則要想es5那樣的寫法,例如 2 在物件中的方法的寫法 es5中物件 substrict function es6中物件 substrict 3 物件的匯出寫法 es5兩種形式 1 module.ex...