So I have written the same functionality using two different coding styles given below:
HTML
<div id="menu">
<button data-action="save">Save</button>
<button data-action="search">Search</button>
</div>
Technique 1 JS:
;(function(window, document, undefined) {
'use strict';
var menu = document.getElementById('menu');
var actions = {
save: function() {
alert("save");
},
search: function() {
alert("search");
}
}
menu.addEventListener('click', function(event) {
var action = event.target.dataset.action;
if(action) {
actions[action]();
}
})
})(window, document);
Technique 2 JS:
;(function(window, document, undefined) {
'use strict';
function Menu(elem) {
this._elem = elem;
elem.onclick = this.onClick.bind(this);
}
Menu.prototype = {
onClick: function(event) {
var action = event.target.dataset.action;
if (action) {
this[action]();
}
},
save: function() {
alert('save');
},
search: function(){
alert('search');
}
};
new Menu(menu); //How is menu directly accessible without actually getting it by Id from the template?
})(window, document);
I have two questions here:
What is the benefit of using technique 2 over technique 1 ?
PS: I know all about prototypal inheritance and how it is useful where 100 different instances of the same class are using functions which are assigned memory only once (given the functions are in the prototype of the constructor function). I just want to know how is it re-usable in this scenario?
In technique 2 , how is element with id "menu" accessible directly by writing the Id name while calling the constructor function? I have not event used
getElementById
there?
Edit
(this answer explains the second question I asked very well)