A good[ish] website
Web development blog, loads of UI and JavaScript topics
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.
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.
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.
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.
Here’s a demo if you want to play around with it:
Comments would go here, but the commenting system isn’t ready yet, sorry.