我想用包装函数在Google Apps脚本中扩展(原型)UiApp,但在运行下面这样的简单示例时,我得到了TypeError。。。我做错了什么?
Object.prototype.addLabel = function(text) {
this.createLabel(text);
return this;
}
function testingxUiApp() {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var app = UiApp.createApplication().setTitle('playing around UiApp').setHeight("250");
var panel = app.createFlowPanel().setId('panel');
app.add(panel);
panel.add(app.addLabel("adding label for testing"));
doc.show(app);
}
感谢
无法扩展UiApp、Document、Spreadsheet和其他高阶类。Google阻止了它。如果执行var isObject = UiApp.createApplication() instanceof Object;
行,则isObject
为false,尽管typeof UiApp.createApplication();
表达式返回object
。
2021年BTW注释:(来自https://b.corp.google.com/issues/36753527)
看起来V8中使用的Reflect可以做到这一点:
Reflect.set(
Reflect.getPrototypeOf(SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Some sheet')),
'myMethod',
function() {
return `From sheet '${this.getSheetName()}' with love`;
}
);
let message = SpreadsheetApp.getActiveSheet().myMethod();
console.log(message); // From sheet 'Sheet1' with love`