I want to create a static property for a class named OuterClass. I want the value of this property to be an instance of another class, which is named InnerClass
.
Here is the inner class. It has a property and a function.
// InnerClass.gs
function InnerClass() {
this.myProperty = 42;
}
InnerClass.prototype.myFunction = function() {
return 43;
};
And here is the outer class, which has only one static property.
// OuterClass.gs
function OuterClass() {
}
OuterClass.innerClass = new InnerClass();
However, when I try to call methods of the inner class, I get:
TypeError: Cannot find function myFunction in object [object Object].
// myScript.gs
function myScript() {
console.log(OuterClass.innerClass.myProperty); // 42.0
console.log(OuterClass.innerClass.myFunction()); // TypeError: Cannot find function myFunction in object [object Object].
var anotherInnerClassInstance = new InnerClass();
console.log(anotherInnerClassInstance.myFunction()); // 43.0
}
Since calling the instance method on anotherInnerClassInstance
works, I believe that I am having trouble with the static property OuterClass.innerClass
because
- The constructor of
InnerClass
is hoisted, butInnerClass.prototype.myFunction
is not. - As
OuterClass.innerClass
is instantiated, it is instantiated with an incomplete instance, becauseInnerClass.prototype.myFunction
was not hoisted, and is not yet attached to the instance created.
Is there a way to use a class instance as a static variable? Note that I have to use prototype-based classes because I'm really using Google Apps Script, which is based on an obsolete version of JavaScript.
For those who have been unable to replicate this problem, here is a link to the Google Sheet producing this error: https://docs.google.com/spreadsheets/d/1Gxylcrbg9rWHGmc68CgHFmZqJ20E5-pLgA6fmHkxhAA/edit?usp=sharing
Also, here's a direct link to the script project: https://script.google.com/d/1V0FYrgiB3a4rTtvd9StyDtWAZ13AqlPl4rpgauCWSKk46UbcdIj9nqJC/edit?usp=sharing