D
D
Dubrovin2018-02-05 22:49:50
JavaScript
Dubrovin, 2018-02-05 22:49:50

How to make a chain function yourself in JS?

I want to create a simple function, let's call it myfunc, which will allow you to store methods inside and call them chained, for example:
myfunc().find( '.selector').on('click', func).css(' somecsshere').
Just like it's done in jQuery, only with its own set of methods.
How can this be done with as few lines as possible and possibly with es6 classes?
ps Please do not offer ready-made solutions, I have reviewed a bunch of them and do not understand how it works (and I want to understand exactly how it works in the first place), please provide a short piece of code that implements this with explanations.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Roman Domoratskii, 2018-02-05
@domoratskii

You need to return the current object each time. This is done by adding return this at the end of each method.

var life = {
  day: 0,
  up() {
    this.day++;
    return this;
  },
  down() {
    this.day--;
    return this;
  },
}

life.up().up()
console.log(life.day) //2

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question