首页 > 其他 > 详细

[TypeScript] Understanding Decorators

时间:2016-06-10 18:58:40      阅读:216      评论:0      收藏:0      [点我收藏+]

Decorators are a feature of TypeScript that are becoming more and more common in many major libraries. This lesson walks you through what decorators are and how to create your own.

 

Nomarl way to decorate a object :

const Person = {name: ‘John‘};

function addAge(age){
    return function(person){
        return {
            age,
            name: person.name
        }
    }
}

const john = addAge(30)(Person);
console.log(john); // {name: "John", age: 30}

 

In Typescript, we can enable "experimentaDecorators", which is ES7 feature:

{
    "compilerOptions": {
        "rootDir": "src",
        "module": "commonjs",
        "target": "es5",
        "noImplicitAny": false,
        "sourceMap": false,
        "outDir": "./dist",
        "noEmitOnError": true,
        "experimentalDecorators": true
    },
    "exclude": [
        "node_modules",
        "typings/main",
        "typings/main.d.ts"
    ]
}

 

function addAge(age){
    return function(targetClass){
        return class{
            age = age;
            name = new targetClass().name;
        }
    }
}

@addAge(30)
class Person{
    name = "Johnn";
}

const john = new Person();
console.log(john); // {name: "Johnn", age: 30}

As before we create addAge function as decorator, different from before, it return class, because we want to decorate Person class.

After the decorator, we will have age prop on the person class.

[TypeScript] Understanding Decorators

原文:http://www.cnblogs.com/Answer1215/p/5573975.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!