Glutch Glutch - 28 days ago 6
Javascript Question

How can i create nested functions

I'm trying to create "nested functions". But i can't seem to find a solution!

const func1 = (value1) => {
const func2 = (value2) => {
console.log(value1 + value2)
}
}

func1(2).func2(3)


What i really want to accomplish is create my own little "jQuery function"

const $ = (element) => {
const addClass = (name) => {
const x = document.querySelectorAll(element);
for (i = 0; i < x.length; i++) {
x[i].className = name
}
}
}

$('#circle').addClass('nice')

Answer

I think this topic is too broad for a single SO question, but here is a very simple example of how you could do this, to get you started:

const $ = (selector) => {
  const items = document.querySelectorAll(selector);

  const self = {
    addClass: (name) => {
      for (let i = 0; i < items.length; i++) {
        items[i].classList.add(name);
      }

      return self;
    },
    removeClass: (name) => {
      for (let i = 0; i < items.length; i++) {
        items[i].classList.remove(name);
      }

      return self;
    }
  };

  return self;
}

$('#circle').addClass('nice').removeClass('bad');
.nice {
  color: green;
}
.bad {
  color: red;
}
.fancy {
  text-decoration: underline;
}
<div id='circle' class='bad fancy'>
  Hello
</div>

Comments