How to add two Objects in objects items

Recently, I’ve asked a question about how to create a shortand for addEventListener, the result was:

var dom = {
  id: function(elementId) {
    var element = document.getElementById(elementId);
    return Object.create(element, {
      on: {
        value(event, fn, options) {
          element.addEventListener(event, fn, options);
        }
      }
    })
  }
};

what if I wanted to add two Object.create? How would I return it? Is it even possible?

20 thoughts on “How to add two Objects in objects items”

  1. If I understand your question correctly, you can add several functions to dom and chain them by returning this inside each function. Then call them like this:

    dom.id("el").on("click",()=>console.log("clicked") ).changeText("replacement text");
    
    var dom = {
      id: function(elementId) {
        var element = document.getElementById(elementId);
        return Object.create(element, {
          on: {
            value(event, fn, options) {
              element.addEventListener(event, fn, options);
              return this;
            }
          },
          changeText: {
            value(text) {
              element.innerText = text;
              return this;
            }
          }
        })
      }
    };
    
    dom.id("el").on("click", () => console.log("clicked") ).changeText("replacement text");
    <div id="el">This text will be replaced</div>
    Reply

Leave a Comment