daG*_*vis 21 javascript return function chain chainable
让我们想象这样的功能:
function foo(x) {
x += '+';
return x;
}
Run Code Online (Sandbox Code Playgroud)
使用它将是:
var x, y;
x = 'Notepad';
y = foo(x);
console.log(y); // Prints 'Notepad+'.
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种方法来创建可与其他功能链接的功能.
想象一下用法:
var x, y;
x = 'Notepad';
y = x.foo().foo().toUpperCase(); // Prints 'NOTEPAD++'.
console.log(y);
Run Code Online (Sandbox Code Playgroud)
我该怎么做?
Ale*_*pin 20
当然,诀窍是在完成修改后返回对象:
String.prototype.foo = function() {
return this + "+";
}
var str = "Notepad";
console.log(str.foo().foo().toUpperCase());
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/Xeon06/vyFek/
为了使方法可用String,我正在修改它的原型.但是请注意不要这样做Object,因为它可能会在枚举其属性时导致问题.
如果我没记错的话,你可以使用"this"作为函数的上下文(它所属的对象)并返回它以使函数可链接.换一种说法:
var obj =
{
f1: function() { ...do something...; return this;},
f2: function() { ...do something...; return this;}
}
Run Code Online (Sandbox Code Playgroud)
然后你就可以把这些电话联系起来 obj.f1().f2()
请记住,通过调用obj.f1().toUpperCase(),你将无法实现你所期望的 - 它将执行f1(),返回"this"并尝试调用obj.toUpperCase().