在 dojojs 中declare
,函数是创建类的一种解决方法,因此接下来的代码:
// Define class A
var A = declare(null, {
myMethod: function(){
console.log("Hello!");
}
});
// Define class B
var B = declare(A, {
myMethod: function(){
// Call A's myMethod
this.inherited(arguments); // arguments provided to A's myMethod
console.log("World!");
}
});
应该相当于:
// Define class A
class A {
myMethod() {
console.log("Hello!");
}
}
// Define class B
class B extends A {
myMethod() {
// Call A's myMethod
super.myMethod(); // arguments provided to A's myMethod
console.log("World!");
}
});
对于第二个示例中显示的多重继承,Typescript 本身并不支持它。这意味着您应该使用辅助函数来执行此操作。例如代码:
define(["dojo/_base/declare",
"dijit/_Widget",
"dijit/_TemplatedMixin",
"dijit/_WidgetsInTemplateMixin".
"text!/some.html"],
function (dojo_declare, _Widget, _TemplateMixin, _WidgetsInTemplateMixin, template) {
var mod =
{
templateString: template,
constructor: function () {
},
postCreate: function () {
// do something here....
this.inherited(arguments);
}
};
return dojo_declare("sample", [_Widget, _TemplateMixin, _WidgetsInTemplateMixin], mod);
});
你可以做:
import declare = require("dojo/_base/declare");
import _Widget = require("dijit/_Widget");
import _TemplateMixin = require("dijit/_TemplatedMixin");
import _WidgetsInTemplateMixin = require("dijit/_WidgetsInTemplateMixin");
import template = require("text!/some.html");
// Most likely you should extend _Widget since it is the one which contains
// the method `postCreate`
class Sample extends _Widget implements _TemplateMixin, _WidgetsInTemplateMixin {
templateString: string = template;
constructor() {}
postCreate() {
// do something here....
super.postCreate(arguments);
}
// here you should put the overridden methods from the `implements` statement
buildRendering: Function;
destroyRendering: Function;
getCachedTemplate: Function;
//...
}
// This line is possibly wrong
applyMixins (Sample, [_TemplateMixin, _WidgetsInTemplateMixin]);
</pre>
函数applyMixins
应该如下所示:
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach(baseCtor => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach(name => {
if (name !== 'constructor') {
derivedCtor.prototype[name] = baseCtor.prototype[name];
}
});
});
}
PD:declare
Typescript 中的关键字是用于创建定义文件(*.d.ts
)而不是用于声明类。如果你想公开任何类、函数或变量,你应该在它们前面加上关键字export
。