LoginSignup
3
3

More than 5 years have passed since last update.

Google Apps Script でクラスの継承を行う

Last updated at Posted at 2019-03-29

概要

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 におけるクラス定義の実現方法

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3