How to implement chained method calls like jQuery?

前端 未结 4 1432
谎友^
谎友^ 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:32

    You are almost there:

    new foo('hello').alertTest('world');
    

    or if you don't like the new:

    var bar = function bar(str) {
        this.str = str;    
    };
    
    bar.prototype = {
        alertTest :  function(additional){
            alert(this.str + ' ' + additional);
            return this;
        }
    };
    
    function foo(str) {
        return new bar(str);
    }
    
    foo('hello').alertTest('world');
    

    Live Demo.

提交回复
热议问题