我可以在带有ES6(V8)的库中的Google Apps脚本中使用已定义的类吗? [英] Can I use in Google Apps Scripts a defined Class in a library with ES6 (V8)?

查看:57
本文介绍了我可以在带有ES6(V8)的库中的Google Apps脚本中使用已定义的类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用库中定义的类,但结果只收到一个错误.

I'm trying to use a class defined in a library but I only receive an error as a result.

[LibraryProject]/library/model/Update.gs

class Update {
  constructor(obj = {}) {
    if(typeof obj == "string"){
      options = JSON.parse(obj);
    }
    Object.assign(this, obj);
  }

  text(){
    return (this.message && this.message.text)?this.message.text:''
  }
}

任务

✅创建项目的新版本.((文件>管理版本...)

✅ Create a new version of the project. (File > Manage versions...)

✅将此库加载到另一个项目中[别名:CustomService] (资源>库...)

✅ Load this library in another project [Alias: CustomService] (Resources > Libraries...)

✅使用CustomService的功能

✅ Use functions of CustomService

❌使用CustomService类

❌ Use class of CustomService

如果我尝试使用Class

If I try to use a Class

[NormalProject]/index.gs

function test  (){
  Logger.log(CustomService.libraryFunction())
  var update = new CustomService.Update("");
  Logger.log(update)
}

TypeError:CustomService.Update不是构造函数(第3街,archivo代码")

TypeError: CustomService.Update is not a constructor (línea 3, archivo "Code")

如何实例化此类的对象?

How can I instantiate an Object of this Class?

如果我跑步...

记录器

推荐答案

如官方文档中所述

库用户仅可使用脚本中的以下属性:

Only the following properties in the script are available to library users:

  • 无数的全局属性
    • 函数声明
    • 变量在函数外部使用var和
    • 创建的
    • 在全局对象上显式设置的属性.

这意味着全局 this 对象中的每个属性都可供库用户使用.

This would mean every property in the global this object are available to library users.

在ES6之前,函数外部的所有声明(以及函数声明本身)都是此全局对象的属性.ES6之后,有两种全局记录:

Before ES6, All declarations outside a function (and function declaration themselves) were properties of this global object. After ES6, There are two kinds of global records:

  • 对象记录-与ES5相同.

  • Object record- Same as ES5.

  • 函数声明
  • 函数发生器
  • 变量分配

声明性记录-新建

  • 其他所有内容- let const class

尽管它们本身是全局变量,但无法从全局对象"访问声明性记录中的那些变量.因此,库用户无法访问库中的类声明.您可以简单地向类添加变量分配,以向全局对象添加属性(任何功能之外):

Those in the declarative record are not accessible from the global "object", though they are globals themselves. Thus, the class declaration in the library is not accessible to library users. You could simply add a variable assignment to the class to add a property to the global object(outside any function):

var Update = class Update{/*your code here*/}

参考文献:

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆