如何在 JavaScript 中创建可链接的函数? [英] How to make chainable function in JavaScript?

查看:21
本文介绍了如何在 JavaScript 中创建可链接的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们想象一下这样的功能:

Lets imagine function like this:

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

它的用法如下:

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.

想象用法:

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

我该怎么做?

推荐答案

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

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/

为了使该方法在 String 上可用,我正在修改它的原型.但是请注意不要在 Object 上执行此操作,因为在枚举其属性时可能会导致问题.

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

这篇关于如何在 JavaScript 中创建可链接的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆