简体   繁体   中英

Prototype displays source code (Google Apps Script/Javascript)

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM