Please note this question is not answered by Self-references in object literals / initializers as that question addresses defining properties in terms of other properites, not methods.
Also, How does the "this" keyword in Javascript act within an object literal? is too high-level a decription of the subject for me to be able to solve my use case.
In Python, I can do this:
class Test:
def __init__(self):
self.id = self.get_id()
def get_id(self):
return 10
t = Test()
print(t.id)
Meaning an object property can be defined in terms of a method of the same object.
In JavaScript, it doesn't work:
var Test = {
id : this.getId(),
getId : function() {
return 10;
}
};
Gives script.js:47 Uncaught TypeError: this.getId is not a function
I've tried defining the id
after the method definition but that didn't work.
How do I do this in JavaScript please?