Robin Andrews
Robin Andrews

Reputation: 3804

JavaScript Define Property in Terms of Method

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

Answers (3)

Evgeny Yudin
Evgeny Yudin

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

Barmar
Barmar

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

see sharper
see sharper

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

Related Questions