clubmate.fi

A good[ish] website

Web development blog, loads of UI and JavaScript topics

Self referencing object literal in JavaScript

Filed under: JavaScript— Tagged with: getter, object

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

Would be cool if this worked:

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:

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:

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:

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:

<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:

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

Comments would go here, but the commenting system isn’t ready yet, sorry.

  • © 2022 Antti Hiljá
  • About
  • All rights reserved yadda yadda.
  • I can put just about anything here, no one reads the footer anyways.
  • I love u!