In my code, I am trying to establish a static property for a class called OuterClass. This static property should hold an instance of another class named InnerClass
.
The InnerClass definition consists of a property and a function as shown below:
// InnerClass.gs
function InnerClass() {
this.myProperty = 42;
}
InnerClass.prototype.myFunction = function() {
return 43;
};
On the other hand, here is the OuterClass definition which only contains the static property:
// OuterClass.gs
function OuterClass() {
}
OuterClass.innerClass = new InnerClass();
However, when I attempt to invoke methods from the inner class, I encounter the following error message:
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
}
Based on my analysis, it seems that the issue lies with the static property OuterClass.innerClass
due to the following reasons:
- The constructor for
InnerClass
gets hoisted, whileInnerClass.prototype.myFunction
does not. - During the instantiation of
OuterClass.innerClass
, it becomes incomplete becauseInnerClass.prototype.myFunction
was not hoisted and therefore not attached to the created instance yet.
I wonder if there is a way to utilize a class instance as a static variable? It's worth noting that I have to work with prototype-based classes since I'm using Google Apps Script which relies on an outdated version of JavaScript.
If you are unable to reproduce this issue, here is the link to the Google Sheet causing the error: https://docs.google.com/spreadsheets/d/1Gxylcrbg9rWHGmc68CgHFmZqJ20E5-pLgA6fmHkxhAA/edit?usp=sharing
Additionally, here is a direct link to the script project: https://script.google.com/d/1V0FYrgiB3a4rTtvd9StyDtWAZ13AqlPl4rpgauCWSKk46UbcdIj9nqJC/edit?usp=sharing