dojojsdeclare
関数では、クラスを作成するための回避策であるため、次のコード:
// 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!");
}
});
2 番目の例で示した多重継承の場合、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
。