How to make chainable function in JavaScript?

送分小仙女□ 提交于 2019-11-26 08:19:11

问题


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?


回答1:


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/

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.




回答2:


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:

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

then you can chain the calls like 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().



来源:https://stackoverflow.com/questions/7730334/how-to-make-chainable-function-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!