如何实现像jQuery这样的链式方法调用? [英] How to implement chained method calls like jQuery?
问题描述
所以我(仍然)完全爱上了全能的jQuery,我有自己不断增长的实用程序库,我想在java脚本对象中编写代码。为了简化我的其他前端开发人员,我想保持类似于jquery的语法。所以我想要这样的东西:
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 to keep syntax similar to that of jquery for the sake of simplicity for my other front end devs. So I want something like this:
foo(argument).method(argument);
我一直在尝试这样的事情:
I have been trying something like this:
var foo = function(str){
this.str = str;
}
foo.prototype = {
alertTest : function(additional){
alert(this.str + ' ' + additional);
}
}
这就是foo('hello')。alertTest( '世界);警告'你好世界'
So that foo('hello').alertTest('world); with alert 'hello world'
我知道这是可能的,但我不是一个OO人,需要帮助才能让这件事变得简单。请帮忙。我还打算有很多foo()。bar();类型函数,如foo()。somethingelse();和foo()。anotherthing(); 。我做了几次尝试,但我在这里努力奋斗。还必须有一个非常棒的方法。
I know this is possible, but I am not an OO guy and need help getting this simple thing right. Please help. I also intend on having many foo().bar(); type functions, like foo().somethingelse(); and foo().anotherthing(); . I have made several attempts, but am struggling hard here. Also there must be an awesome tight way of doing it.
谢谢大家!
推荐答案
你几乎就在那里:
new foo('hello').alertTest('world');
或者如果您不喜欢 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');
现场演示。
这篇关于如何实现像jQuery这样的链式方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!