How to implement chained method calls like jQuery?

前端 未结 4 1429
谎友^
谎友^ 2020-12-17 02:07

So I am (still) completely in love with the almighty jQuery, and I have my own growing library of utilities that I want to codify in a java-script object. And I would like t

4条回答
  •  萌比男神i
    2020-12-17 02:32

    It is quite late to answer this question and also jquery is quite deprecated. But still people get asked this question quite frequently.

    I would implement like below without using prototype -

    const wrapper = (person) => ({
        sayGoodMorning:() => {
            console.log("Good Morning, "+person.name)
            return wrapper(person);
        },
        showAlert:() => {
           alert("Hey I am alert");
           return wrapper(person);
        },
        sayGoodEvening:() => {
            console.log("Good Evening, " + person.name)
            return wrapper(person);
        },
        sayGoodNight:() => {
            console.log("Good Night, " + person.name)
            return wrapper(person);
        },
      });
      const person = {name:"StackOverflow"};
      const $ = (obj) => wrapper(obj);
      const $example = $(person);
      
      $example
        .showAlert()
        .sayGoodMorning()
        .sayGoodEvening()
        .sayGoodNight();

提交回复
热议问题