Subclasses and inheritance in the Google Script application

Does anyone have templates for recording and subclassing objects in a Google Script application? (JavaScript can be used in Google Docs.) I tried to define subclasses using ParentClass.call (this, args) and put the methods of the parent class both in the original definition of the parent and assign them to ParentClass.prototype. But while this code passes unit tests, it does not work when used in the Google Script application.

+4
source share
2 answers

it's about class extension (but javascript doesn't have a real "class"). Can you use Prototype.js or mootool.js or do this?

 function Human ( ) { this.init.apply ( this, arguments ); } Human.prototype ={ init: function ( ) { var optns = arguments[0] || {}; this.age = optns.age || 0; this.name = optns.name || "nameless"; }, getName : function ( ) { return this.name; }, getAge : function ( ) { return this.age; } } function Man ( ) { this.init.apply ( this, arguments ); } Man.prototype = { init : function ( ) { Human.prototype.init.apply (this, arguments); this.sex = "man"; }, getName : Human.prototype.getName, getAge : Human.prototype.getAge, getSex : function ( ) { return this.sex; } } function Woman ( ) { this.init.apply ( this, arguments ); } Woman.prototype = { init : function ( ) { Human.prototype.init.apply (this, arguments); this.sex = "woman"; }, getName : Human.prototype.getName, getAge : Human.prototype.getAge, getSex : Man.prototype.getSex } var human = new Human({age:60,name:"Tom Tomas"}), man1 = new Man({age:30,name:"Wood Tomas"}), woman1 = new Woman({age:19,name:"Mary Tomas"}); console.log( human.getName() ); console.log( man1.getName() ); console.log( woman1.getName() ); console.log( human.getAge() ); console.log( man1.getAge() ); console.log( woman1.getAge() ); console.log( human.getSex && human.getSex() ); console.log( man1.getSex() ); console.log( woman1.getSex() ); 

or you can use jQuery $ .extend for this. desire can help!

+3
source

This should make you:

 var ApiService = { /** * @params {string} bloggerId The ID of your Blog * @returns {array} Posted entries */ getPosts: function (blogID) { var feed = sendRequest_(feedUrl+blogID +"/posts/default"); return feed; } }; /** * First ParentClass (top level parent) */ ApiService.parent = function (parent) { this.parent = parent; }; var ParentClass = ApiService.parent.prototype; /** * Gets the title of a post * * @param {object) post An XML post entry * @returns {string} The title of the post */ ParentClass.getTitle = function () { return this.parent.getElement('title').getText(); }; 

You would use it like:

 var firstTitle = ApiService.getPosts()[0].getTitle(); 
0
source

Source: https://habr.com/ru/post/1400490/


All Articles