在Typescript中如何设置一个新类作为原型?

时间:2017-06-06 16:52:55

标签: javascript typescript

这是我想要实现的输出:

MyTypeScriptClass.prototype = new ko.templateEngine();

这是我的TypeScript:

module Knockout {
    export class MyTypeScriptClass implements KnockoutNativeTemplateEngine {
        allowTemplateRewriting: boolean = false;

        renderTemplateSource(templateSource, bindingContext, options) {
            // does some custom work
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您应该可以使用以下内容:

import * as ko from "knockout";

export class MyTypeScriptClass extends ko.templateEngine {
    allowTemplateRewriting: boolean = false;

    public renderTemplateSource(
        templateSource: Object,
        bindingContext: KnockoutBindingContext,
        options: Object) {

            return /* does some custom work */;
    }
}

输出ES5代码完全不同,因为它使用__extends帮助程序:

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};

var ko = require("knockout");

var MyTypeScriptClass = (function (_super) {
    __extends(MyTypeScriptClass, _super);
    function MyTypeScriptClass() {
        var _this = _super.apply(this, arguments) || this;
        _this.allowTemplateRewriting = false;
        return _this;
    }
    MyTypeScriptClass.prototype.renderTemplateSource = function (templateSource, bindingContext, options) {
        return [];
    };
    return MyTypeScriptClass;
}(ko.templateEngine));

exports.MyTypeScriptClass = MyTypeScriptClass;

但行为应该是一样的。