PropertiesService in Google Apps Script libraries

2019-04-12 08:39发布

问题:

Until Google extends the import/export API to container-bound Apps Script projects, I have moved most of my project to an library which can use that API, and then made Google Docs project into a shell that just calls through to the library.

My problem is having the library access the same properties (PropertiesService) as the Google Doc project. Since I have existing users of my Docs Add-on, I need to keep using these properties.

In my Google Doc project, I tried

$.PropertiesService = PropertiesService;

(where $ is my library).

It didn't work. The library kept using its own properties.

So then I tried.

function _mock(obj) {
  var ret = {};
  for(var key in obj) {
    if(typeof obj[key] == 'function') {
      ret[key] = obj[key].bind(obj);
    } else {
      ret[key] = obj[key];
    }
  }
  return ret;
}

$.PropertiesService = _mock(PropertiesService);

Still not working. Trying again:

function _mock(obj) {
  var ret = {};
  for(var key in obj) {
    if(typeof obj[key] == 'function') {
      ret[key] = (function(val) {
        return function() {
          return val.apply(obj, arguments);
        };
      })(obj[key]);
    } else {
      ret[key] = obj[key];
    }
  }
  return ret;
}

$.PropertiesService = _mock(PropertiesService);

This works.


At this point, I'm wondering:

  1. Why did the first two ways not work, but the third way did?

  2. Can I expect this to continue working?

  3. Is there a better way to have a library access the main script's properties?

Documentation is sparse. There is this, but the PropertiesService is not mentioned.