TypeScript:如何生成构造函数?

时间:2016-09-07 00:05:59

标签: javascript typescript constructor

我想在TypeScript上创建正确的构造函数,但我有问题。我尝试了很多选择,但结果仍然没有:(

我的上一版TS代码:open Playground

Typescript追加到我的代码多余功能: enter image description here

查看生成的代码:

(function () {
    function UserModule(arg1, arg2, arg3) {
        var UserModule = (function () {
            function UserModule(section, where) {
                this.arg1 = arg1;
                this.arg2 = arg2;
                this.arg3 = arg3;
                this.section = section;
                this.getElem('');
                return this;
            }
            UserModule.prototype.getElem = function (new_elem) {
                this.section + this.arg1;
                return this;
            };
            return UserModule;
        }());
    }
})();

我想要代码:

(function () {
    function UserModule(arg1, arg2, arg3) {
            function UserModule(section, where) {
                this.arg1 = arg1;
                this.arg2 = arg2;
                this.arg3 = arg3;
                this.section = section;
                this.getElem('');
                return this;
            }
            UserModule.prototype.getElem = function (new_elem) {
                this.section + this.arg1;
                return this;
            };
            return UserModule;
    }
})();

请帮我删除此功能。谢谢大家!

1 个答案:

答案 0 :(得分:0)

您不应该更改已编译的JavaScript文件。多余的'函数用于在JavaScript中为您实现class UserModule

更新

您希望创建不同的服务实例。通过在服务提供者函数中本地定义服务类,在TypeScript中实现角度工厂非常简单。

请参阅以下实施:

interface IUserModelService {
    getElement: (param: string) => string;
}

function UserModelServiceProvider(
    $scope: ng.IScope,
    $http: ng.IHttpService
) {
    class UserModelService implements IUserModelService {
        constructor(
            private selection: string,
            private where: string
        ) { }
        public getElement(param: string) {
            return param + this.selection + this.where;
        }
    }
    return (selection: string, where: string) => {
        return new UserModelService(selection, where);
    };
}

yourAngularApp.factory("userModel", UserModelServiceProvider);

然后你可以注入这个" userModel"进入您的控制器,并使用它来创建您的服务实例。