如何在 JavaScript 中创建可链接的函数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7730334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 01:06:10  来源:igfitidea点击:

How to make chainable function in JavaScript?

javascriptfunctionreturnchainchainable

提问by daGrevis

Lets imagine function like this:

让我们想象一下这样的函数:

function foo(x) {
    x += '+';
    return x;
}

Usage of it would be like:

它的用法如下:

var x, y;
x = 'Notepad';
y = foo(x);
console.log(y); // Prints 'Notepad+'.

I'm looking for a way to create function that's chainable with other functions.

我正在寻找一种方法来创建可与其他函数链接的函数。

Imagine usage:

想象一下用法:

var x, y;
x = 'Notepad';
y = x.foo().foo().toUpperCase(); // Prints 'NOTEPAD++'.
console.log(y);

How would I do this?

我该怎么做?

采纳答案by Alex Turpin

Sure, the trick is to return the object once you're done modifying it:

当然,诀窍是在完成修改后返回对象:

String.prototype.foo = function() {
    return this + "+";
}

var str = "Notepad";
console.log(str.foo().foo().toUpperCase());

http://jsfiddle.net/Xeon06/vyFek/

http://jsfiddle.net/Xeon06/vyFek/

To make the method available on String, I'm modifying it's prototype. Be careful not to do this on Objectthough, as it can cause problems when enumerating over their properties.

为了使该方法在 上可用String,我正在修改它的原型。但是要小心不要这样做Object,因为它会在枚举它们的属性时导致问题。

回答by Andrey

If I remember correctly, you can use "this" as a context of a function (object it belongs to) and return it to make the function chainable. In other words:

如果我没记错的话,您可以使用“this”作为函数(它所属的对象)的上下文并返回它以使函数可链接。换句话说:

var obj = 
{
    f1: function() { ...do something...; return this;},
    f2: function() { ...do something...; return this;}
}

then you can chain the calls like obj.f1().f2()

然后你可以像这样链接调用 obj.f1().f2()

Keep in mind, you won't be able to achieve what you are expecting by calling obj.f1().toUpperCase() - it will execute f1(), return "this" and will try to call obj.toUpperCase().

请记住,您将无法通过调用 obj.f1().toUpperCase() 来实现您的期望——它将执行 f1(),返回“this”并尝试调用 obj.toUpperCase()。