编程语言
首页 > 编程语言> > javascript-剥离成员函数的Google Apps脚本服务器中的对象

javascript-剥离成员函数的Google Apps脚本服务器中的对象

作者:互联网

由于某些原因,从Google Apps脚本项目的服务器端返回的对象会将任何成员函数替换为null.以下是一些示例代码演示了这一点:

服务器

function A() {
  this.a = 'a string';
  this.toString = function() { return this.a; }
  this.innerObj = { b : "B", toString : function(){ return 'inner object'; } }
}

function getA() { return new A(); }

clientJS.html; / *或控制台,如果您愿意… * /

google.script.run.withSuccessHandler(console.log).getA();

对象在原始打印时看起来像这样:

{ "a": "a string", "toString": null, "innerObj": { "b": "B", "toString": null } }

Live demo of the problem

我该怎么办?

解决方法:

这是设计使然,如前所述in the documentation

Legal parameters and return values are JavaScript primitives like a Number, Boolean, String, or null, as well as JavaScript objects and arrays that are composed of primitives, objects and arrays. […] Requests fail if you attempt to pass a Date, Function, DOM element besides a form, or other prohibited type, including prohibited types inside objects or arrays.

解决方法是,您可以stringify an object with its methods

JSON.stringify(obj, function(key, value) {
  if (typeof value === 'function') {
    return value.toString();
  } else {
    return value;
  }
});

然后在接收端reconstruct the functions from strings.

标签:google-apps-script,javascript
来源: https://codeday.me/bug/20191025/1930122.html