如何在JavaScript中创建可链接的功能? [英] How to make chainable function in JavaScript?
本文介绍了如何在JavaScript中创建可链接的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
pre $
function foo(x){
x + ='+';
return x;
}
它的使用方式如下所示:
var x,y;
x ='记事本';
y = foo(x);
console.log(y); //打印'记事本+'。
我正在寻找一种创建可与其他函数链接的函数的方法。 b
$ b
想象一下用法:
var x,y;
x ='记事本';
y = x.foo()。foo()。toUpperCase(); //打印'NOTEPAD ++'。
console.log(y);
我会怎么做?
解决方案
当然,诀窍是在完成修改后返回对象:
String.prototype.foo = function(){
return this ++;
}
var str =记事本;
console.log(str.foo()。foo()。toUpperCase());
http: //jsfiddle.net/Xeon06/vyFek/
要使方法在 String
上可用,我正在修改它的原型。但请注意不要在 Object
上执行此操作,因为枚举其属性时可能会导致问题。
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?
解决方案
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.
这篇关于如何在JavaScript中创建可链接的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文