2

GAS is super weird: If I add a prototype to a function, the source code of the prototype is added to every instance of the function.

function createPerson() {
var me = new Person("Ben", "Jamin");
Logger.log(me);
};

function Person(firstname, lastname) {
  this.firstname = firstname;
  this.lastname = lastname;
};

Person.prototype.member = function() {
  return "yes"
};

This is what it logs to the console:

[15-04-13 11:47:12:351 CEST] {member= function () { return "yes"; } , lastname=Jamin, firstname=Ben}

What am I doing wrong?

1 Answer 1

0

Not a prototype whiz but you can access your objects like:

Logger.log("%s %s is a member? %s",me.firstname,me.lastname,me.member());

Look at the following:

function createPerson() {
  var me = new Person("Ben", "Jamin", false);
  var you = new Person("Bint", "Jamin", true);
  Logger.log("%s %s is a member? %s",me.firstname,me.lastname,me.isMember());
  Logger.log("%s %s is a member? %s",you.firstname,you.lastname,you.isMember());
};

function Person(firstname, lastname, member) {
  this.firstname = firstname;
  this.lastname = lastname;
  this.member = member;
};

Person.prototype.isMember = function() {
  return this.member;
};

When a Person is created isMember IS attached to the new object. It inherits the object reference "this". You still need to access it as a function to evaluate the code. Someone can probably correct me but this isnt a Apps Script quark it is how javascript works.

Sign up to request clarification or add additional context in comments.

3 Comments

Yes. Same happen cif you use prototypes in client javascript. Function is just another property of the object. thats normal javascript.
Thanks for the answer, probably works. My problem is that the entire code is saved in the instance. Maybe it's just appearance, but it just does not look like it is supposed to be that way.
That is how it works. Even in plain javascript if you console.log 'me'. It will return a reference to the function not the evaluated code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.