0
votes

Thanks to this answer, I've been able to invoke generic functions with any number of parameters. But as I was further refining my code, I came across this problem:

function test() {
  var object = {to: "[email protected]", subject: "subject line", body: "using object"};
  var attributes = ["[email protected]", "subject line", "using attributes"];
  pass_to_func1(MailApp.sendEmail, attributes); 
  pass_to_func2(MailApp.sendEmail, object);
}

function pass_to_func1(func, attributes) {
  try {
    func.apply(null, attributes);
  }
  catch (e) {
    Logger.log(e.name + ": " + e.message);
    return;
  }
  Logger.log("pass_to_func1 success");
}

function pass_to_func2(func, object) {
  try {
    func.call(null, object);
  }
  catch (e) {
    Logger.log(e.name + ": " + e.message);
    return;
  }
  Logger.log("pass_to_func2 success");
}

As you can see, I am trying to pass the MailApp.sendEmail funtion value as an argument to a "middle-man" function, of which I have two versions.

One invokes the function parameter with Function.prototype.apply with an array of strings as its argument (send-to email, subject, body).

The other invokes the function parameter with Function.prototype.call with a javascript object as its argument (see the MailApp developer reference for more info).

Both of them throw the same error, shown below:

InternalError: Method "sendEmail" was invoked with [object Object] as "this" value that can not be converted to type MailApp.

I don't know how to make sense of an error like that and I would appreciate any help.

1
Look up Function::call and Function::apply in MDN's javascript reference. You probably haven't 'scoped' the function call to the right object (which I suspect should be MailApp in this case) - TheAddonDepot
I actually just figured this out as well! Thank you for helping anyway, you were right on - Manuel

1 Answers

0
votes

So I just figured out what the problem is.

I needed to replace

func.apply(null, attributes); and func.call(null, object);

with

func.apply(MailApp, attributes);

and func.call(MailApp.object);