Reputation: 3804
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?
Upvotes: 0
Views: 41
Reputation: 143
var Test = {
get id() {
return 10
}
}
console.log(Test.id)
https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Functions/get
or
var Test = {
get id () {
return this.getId()
},
getId: function () {
return 10
}
}
console.log(Test.id)
Upvotes: 2
Reputation: 782785
You can only use this
inside a method. There's no way to reference the current object in an object literal.
But you can refer to it after the object is created.
var Test = {
getId : function() {
return 10;
}
};
Test.id = Test.getId()
Upvotes: 0
Reputation: 12055
The other answer (Evgeny Yudin) is simpler - but this is an alternative using classes that may add something to your understanding.
class Test {
constructor() {
this.id = this.getId();
}
getId() {
return 10;
}
}
console.log((new Test()).id); //outputs 10
Upvotes: 3