0

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')
5
  • developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes Commented Nov 8, 2016 at 12:42
  • 2
    the term you are looking for is called "function chaining" - what you are doing right now is nowhere near what you are trying to accomplish Commented Nov 8, 2016 at 12:42
  • func1(2).func2(3) – Here func1() returns an object which has a method func2 Commented Nov 8, 2016 at 12:47
  • you have to return this :) Commented Nov 8, 2016 at 12:52
  • Can someone provide an example where "func1(2).func2(3)" is possible? Commented Nov 8, 2016 at 13:04

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Thats awesome, thank you! What is this called exactly? :)
I don't know of a specific name for the code structure above, but the term for calling one method after another like that is called "method chaining" or a "fluent interface."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.