docs: edit decorator

This commit is contained in:
ruanyf
2017-06-07 17:32:28 +08:00
parent 17b1f45c6b
commit 6b56bb10bb
+37 -1
View File
@@ -2,7 +2,7 @@
## 类的修饰
修饰器(Decorator)是一个函数,用来修改类的行为。这是 ES 的一个[提案](https://github.com/wycats/javascript-decorators),目前 Babel 转码器已经支持。
修饰器(Decorator)是一个函数,用来修改类的行为。ES2017 引入了这项功能,目前 Babel 转码器已经支持。
```javascript
@testable
@@ -118,6 +118,23 @@ let obj = new MyClass();
obj.foo() // 'foo'
```
实际开发中,React 与 Redux 库结合使用时,常常需要写成下面这样。
```javascript
class MyReactComponent extends React.Component {}
export default connect(mapStateToProps, mapDispatchToProps)(MyReactComponent);
```
有了装饰器,就可以改写上面的代码。
```javascript
@connect(mapStateToProps, mapDispatchToProps)
export default class MyReactComponent extends React.Component {}
```
相对来说,后一种写法看上去更容易理解。
## 方法的修饰
修饰器不仅可以修饰类,还可以修饰类的属性。
@@ -289,6 +306,25 @@ readOnly = require("some-decorator");
总之,由于存在函数提升,使得修饰器不能用于函数。类是不会提升的,所以就没有这方面的问题。
另一方面,如果一定要修饰函数,可以采用高阶函数的形式直接执行。
```javascript
function doSomething(name) {
console.log('Hello, ' + name);
}
function loggingDecorator(wrapped) {
return function() {
console.log('Starting');
const result = wrapped.apply(this, arguments);
console.log('Finished');
return result;
}
}
const wrapped = loggingDecorator(doSomething);
```
## core-decorators.js
[core-decorators.js](https://github.com/jayphelps/core-decorators.js)是一个第三方模块,提供了几个常见的修饰器,通过它可以更好地理解修饰器。