How to implement chained method calls like jQuery?

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

    I did something like this a while ago and it was a ton of fun to create!

    If i remember correctly, To be able to use dot-operators, I had to return the object as part of the original function call. This way I could chain lots of stuff together like $(id).value('asdf').color('#ff0000')

    function $(id){
        this.e = document.getelementbyid(id)
        me = this
        this.val = function (newval) {
            this.e.value = newval;
            return me;  // <- Important
        };
        return this;  //  <- Important
    }
    
    $("textbox1").val("New Value")    // changes textbox1's value to "New Value"
    

    If it helps for reference: http://www.mikedoesweb.com/vis/

提交回复
热议问题