【发布时间】:2021-11-19 09:21:25
【问题描述】:
Google 应用程序脚本提供了一个library feature,如果您在其中包含项目密钥,则会添加一个库作为全局对象。我正在寻找迭代添加库的所有功能。这在带有for...in 循环的rhino 引擎中曾经是可能的。但我无法遍历 v8 引擎中库的任何属性。
在 V8 运行时中,项目及其库在不同的执行上下文中运行,因此具有不同的全局和原型链。
谁能解释这个对象是如何创建的或如何访问它的所有属性?
项目A:
function testLib(prop = 'main') {
const isEnumerable = MyLibrary.propertyIsEnumerable(prop);
const isOwnProperty = MyLibrary.hasOwnProperty(prop);
console.info({ isEnumerable, isOwnProperty }); // { isEnumerable: false, isOwnProperty: true }
console.info(prop in MyLibrary);//true
for (const property in MyLibrary) {
//loop doesn't start
console.info(property);
}
console.info(Object.getOwnPropertyDescriptor(MyLibrary, prop)); //logs expected data:
/*{ value: [Function: main],
writable: true,
enumerable: false,
configurable: true }*/
console.log(Object.getOwnPropertyDescriptors(MyLibrary)); //actual: {} Expected: array of all functions including `main`
MyLibrary.a = 1;
console.log(Object.getOwnPropertyDescriptors(MyLibrary)); //actual: {a:1} Expected: array of all functions including `main`
}
function testPropDescriptors() {
const obj = { prop1: 1, b: 2 };
console.log(Object.getOwnPropertyDescriptors(obj)); //logs expected data
/*{prop1: { value: 1, writable: true, enumerable: true, configurable: true },
b: { value: 2, writable: true, enumerable: true, configurable: true } }*/
}
我的图书馆(项目 B):
function main(){}
function onEdit(){}
为了重现,
- 通过clicking here 创建一个新项目 - 比如项目 A
-
Create a another script project(比如项目 B):
- 在项目 B 中添加一个名为
main的函数并 - Deploy it 点击右上角的部署。
-
add it's key 在项目 A 中并将其命名为
MyLibrary。
- 在项目 B 中添加一个名为
- 将以上脚本复制粘贴到项目A中,选择
testLib函数点击运行
【问题讨论】:
-
我怀疑
Proxy的ownKeystrap 实现已损坏 -
@Bergi 谢谢。无论如何要测试你的理论?显然,
instanceof不能用于测试MyLibrary是否为proxy。即使是Proxy,你有没有看到任何迭代的方法? -
虽然我不确定我是否能正确理解您的问题,但我提出了 2 个解决方法,用于从客户端检索库端的属性和函数。你能确认一下吗?如果我误解了您的问题并且没有用,我深表歉意。
-
@TheMaster 你能得到脚本的调试连接吗?调试器应该能够判断它是否是代理(或者,在给定环境的情况下,更可能是具有在本机代码中实现的相同行为的本机对象)。
-
@Bergi 有一个调试器,它将
MyLibrary列为全局对象,例如:MyLibrary:{},带有“扩展”对象选项。但是“展开”按钮什么也不做(不像其他全局对象,如Array:{}或Proxy:{},它展开以显示对象属性)。
标签: rhino v8 javascript google-apps-script libraries v8 global-object