How to implement chained method calls like jQuery?

前端 未结 4 1427
谎友^
谎友^ 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条回答
  •  抹茶落季
    2020-12-17 02:45

    Something I did really quick but you can relate to the essence of what we are trying to achieve here -

    function ChainingObj() {
      if (!(this instanceof ChainingObj)) {
        return new ChainingObj();
      }
    }
    
    ChainingObj.prototype.first = function() {
      console.log("foo");
      return this; //important to return this.
    }
    
    
    ChainingObj.prototype.second = function() {
      console.log("bar");
      return this;
    }
    
    var a = ChainingObj().first().second();
    

提交回复
热议问题