0

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)

Rahul Arora
  • 4,503
  • 1
  • 16
  • 24
  • The first part of the question probably belongs to [CodeReview.SE](https://codereview.stackexchange.com/), and the second part of the question has been answered [here](https://stackoverflow.com/a/3434388/5894241). – Nisarg Shah Sep 23 '17 at 05:46
  • @NisargShah: I think the first part belongs here only. I do not want my code to be reviewed but want to know the benefit of using one technique over the other with examples. – Rahul Arora Sep 23 '17 at 05:48

0 Answers0