Hammerbot
Hammerbot

Reputation: 16364

Can we make a variable work as a getter in Javascript?

In Javascript we can write:

var obj = {
  log: ['a', 'b', 'c'],

  get latest() {
    if (this.log.length == 0) {
      return undefined;
    }
    return this.log[this.log.length - 1];
  }
}

console.log(obj.latest); // Outputs "c"

From: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get

Now, I have to call obj[key] to make the getter work. Now:

let obj = {
    get root () {
        return 2
    }
}

console.log(obj) // Returns { root: [Getter] }, I would like it to return "2"

Can we make obj return 2 in some way?

Upvotes: 1

Views: 83

Answers (2)

Alexandre Elshobokshy
Alexandre Elshobokshy

Reputation: 10922

To call the function you need to call it using obj.root

let obj = {
  get root() {
    return 2
  }
}

console.log(obj.root)

On the other hand you could simply write obj = obj.root

let obj = {
  get root() {
    return 2
  }
}
obj = obj.root
console.log(obj)

Upvotes: 3

JasonK
JasonK

Reputation: 5294

You could use a IIFE (Immediately Invoked Function Expression) to run the fuction as soon as it is defined.

let obj = {
    root: (function() {
        return 2;
    })()
}

console.log(obj);

This will give the desired output. Note that in this case the IFFE does not add much value as it would be the same as simply defining root: 2 on the object.

Upvotes: 2

Related Questions