I am learning about the object literal pattern. Here is a pretty simple example of an object (es5) with some navigation functionality using jQuery. Take note of how this
refers to the object navigation
.
(function() {
var navigation = {
init: function() {
this.cacheDom();
this.bindEvents();
},
cacheDom: function() {
this.$nav = $('nav');
this.$hamburger = $('button.ham');
},
bindEvents: function() {
this.$hamburger.click(this.toggleNav.bind(this));
},
toggleNav: function() {
this.$nav.toggleClass('active');
}
}
navigation.init();
})()
In ES6 and am having trouble understanding why I cannot reference this in the same way. Example code block:
(function() {
var navigation = {
init: () => {
console.log(this)
navigation.cacheDom();
navigation.bindEvents();
},
cacheDom: () => {
navigation.$nav = $('nav');
navigation.$hamburger = $('button.ham');
},
bindEvents: () => {
navigation.$hamburger.click(this.toggleNav.bind(this));
},
toggleNav: () => {
navigation.$nav.toggleClass('active');
}
}
navigation.init();
})()
In the above example this
will log to the console. How can I let my object know that this refers to the object?
Any help appreciated, Thanks