如何为本地使用编写jquery可链接函数?

Rom*_*ats 5 javascript jquery method-chaining

如何编写可链接的函数但不污染$ .fn?编写函数仅用于在我的插件中使用.可能吗?

$('.myclass').makeSomething().andOneMoreFunction().andLast();
Run Code Online (Sandbox Code Playgroud)

这是正确的方法吗?

UPD.在我的情况下,最好的解决方案是扩展方法:

String.prototype.getMyLength = function(){return this.length;}
Run Code Online (Sandbox Code Playgroud)

现在我可以将此函数应用于任何字符串,如下所示:

var mystring = "test";
mystring.getMyLength();
Run Code Online (Sandbox Code Playgroud)

要么

"teststring".getMyLength()
Run Code Online (Sandbox Code Playgroud)

并使其可链接:

String.prototype.getMe = function(){return this;}
"string".getMe().getMe().getMe().getMe().getMe();
Run Code Online (Sandbox Code Playgroud)

谢谢你的回答!

Nie*_*els 5

你可以链接你想要的一切.如果你定义了$.fn自己,那么return this在你的功能结束时你很重要.

如果你想自己写一些javascript,你也可以链!这取决于你的回归.因此,如果您返回其他对象,则可以从该对象链接.返回值用于此目的.

var obj = {
    test : function(){ 
        alert("Y"); 
        return this; 
    },
    test2 : function(){ 
        alert("2"); 
        return this; 
    }
}
obj.test().test2(); // And so on since it returns this
Run Code Online (Sandbox Code Playgroud)

jQuery插件API

$.fn.test = function(){
    var methods = {
        method0 : function(){
            alert("method0");
            return this;
        }
    };
    return methods;
}
var api = $("obj").test(); // Returns methods
api.method0(); // Calling a function from the returned methods.
// OR
$("obj").test().method0();
Run Code Online (Sandbox Code Playgroud)

上面的函数不再是jQuery可链接的.所以你不能使用,$("obj").test().addClass("test")因为你返回自己的API!