概要
Google Apps Script で親クラスを継承した子クラスを作成するためのメモ。
Google Apps Script は ES6 非対応のため Object.setPrototypeOf() などが使用できない。
方法
Object.setPrototypeOf() の代わりに継承用の関数を作成して使用する。
継承用の関数を作成
inherits
function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
クラスの作成と継承
class
function parentClass(arg){
/* コンストラクタ */
}
function childClass(arg){
parentClass.call(this, arg); // 親クラスのコンストラクタを呼び出す
}
inherits(childClass, parentClass); // prototype を継承
コード例
test
function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
}
function test(){
function parentClass(arg){
this.property1 = arg;
}
parentClass.prototype.property2 = 'fuga';
function childClass(arg){
parentClass.call(this, arg);
}
inherits(childClass, parentClass);
var instance = new childClass('hoge');
Logger.log(instance.property1); // 'hoge'
Logger.log(instance.property2); // 'fuga'
}
参考
ES5なJavascriptでモダンなクラス的継承&スーパー呼び出し
Google流 JavaScript におけるクラス定義の実現方法