# Self referencing object literal in JavaScript

In other words: how to access objects values within the object itself.

Would be cool if this worked:

```js
var wontWork = {
  a: 42
  b: 'meaning of life is ',
  c: this.b + this.a
};
console.log(wontWork); // Meaning of life is 42
```

But it won’t, a getter is needed.

## Getter

The humble `get`, your good friend:

```js
var worksJustFine = {
  a: 42,
  b: 'meaning of life is ',
  get c() {
    return this.b + this.a
  },
}
console.log(worksJustFine.c)
```

Here's what the
[bible says about `get`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get):

> Sometimes it is desirable to allow access to a property that returns a
> dynamically computed value, or you may want to reflect the status of an
> internal variable without requiring the use of explicit method calls. In
> JavaScript, this can be accomplished with the use of a getter. It is not
> possible to simultaneously have a getter bound to a property and have that
> property actually hold a value, although it is possible to use a getter and a
> setter in conjunction to create a type of pseudo-property.

## Reference self from function

If the value in an object is a function, then `this` works as without get:

```js
var foo = {
  a: 'bar',
  b: 'baz',
  c: function () {
    // Works :)
    return this.a + this.b
  },
}
console.log(foo.c()) // barbaz
```

In essence, `get` is syntactic sugar sprinkled over this.

## HTML element object

Another example. Take the below HTML:

```html
<div class="module">
  <h1 class="title">
    Hello world
    <span class="title__icon"></span>
  </h1>
  <ul class="nav">
    <li class="nav__item">Item 1</li>
    <li class="nav__item">Item 2</li>
  </ul>
  <div class="entry">Lorem ipsum dolor sit amet...</div>
</div>
```

Make a self referencing object that contains all the needed HTML elements:

```js
var els = {
  module: document.getElementById('module'),
  get title() {
    return this.module.querySelector('.title')
  },
  get nav() {
    return this.module.querySelector('.nav')
  },
  get navItems() {
    return this.module.querySelectorAll('.nav__item')
  },
  get entry() {
    return this.module.querySelector('.entry')
  },
}
```

Is this better than just using variables? I'm not sure if it's worth the effort,
at least this way the global namespace is not polluted so much.

## Demo

Here’s a demo if you want to play around with it:

[JS Bin on jsbin.com](http://jsbin.com/bamira/embed?js,console)[script](http://static.jsbin.com/js/embed.min.js?3.34.3)
