如何实现像jQuery这样的链式方法调用?

Fre*_*all 6 javascript object

所以我(仍然)完全爱上了全能的jQuery,我有自己不断增长的实用程序库,我想在java脚本对象中编写代码.为了简化我的其他前端开发人员,我想保持类似于jquery的语法.所以我想要这样的东西:

 foo(argument).method(argument);
Run Code Online (Sandbox Code Playgroud)

我一直在尝试这样的事情:

var foo = function(str){
    this.str = str;
}

foo.prototype = {
    alertTest  :  function(additional){
         alert(this.str + ' ' + additional);
    }
}
Run Code Online (Sandbox Code Playgroud)

那就是foo('你好').alertTest('world); 提醒'你好世界'

我知道这是可能的,但我不是一个OO人,需要帮助才能让这件事变得简单.请帮忙.我还打算有很多foo().bar(); 类型函数,如foo().somethingelse(); 和foo().anotherthing(); .我做了几次尝试,但我在这里努力奋斗.还必须有一个非常紧凑的方式来做到这一点.

谢谢大家!

Dar*_*rov 5

你快到了:

new foo('hello').alertTest('world');
Run Code Online (Sandbox Code Playgroud)

或者如果你不喜欢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');
Run Code Online (Sandbox Code Playgroud)

现场演示.