javascript的链接方法 [英] Chaining methods with javascript
问题描述
我正在尝试使用类似于jquery的javascript方法创建链接.请让我知道如何使用javascript来实现链接.
I'm trying to create chaining with the javascript methods similar to what we have with jquery. Please let me know how to implement chaining with javascript.
var controller = {
currentUser: '',
fnFormatUserName: function(user) {
this.currentUser = user;
return this.currentUser.toUpperCase();
},
fnCreateUserId: function() {
return this.currentUser + Math.random();
}
}
var output = controller.fnFormatUserName('Manju').fnCreateUserId();
推荐答案
正如我已经解释的那样,由于您要从 fnFormatUserName
返回一个字符串,因此无法将其用于链接.
As I already explained, since you are returning a string from fnFormatUserName
you cannot use it for chaining.
要启用链接,您需要返回被调用方法的对象.因此,您不能使用getter方法进行链接.
To enable chaining, you need to return the object which invoked method. So, you cannot use getter methods for chaining.
在您的示例中,处理该问题的方法是使getter方法和带有更新对象的方法可用,这些对象可用于链接,例如
In your example, the way to handle it is to have getter methods and methods with updates the object which can be used for chaining like
var controller = {
currentUser: '',
fnFormatUserName: function(user) {
this.currentUser = user.toUpperCase();
return this;
},
fnCreateUserId: function() {
this.userId = this.currentUser + Math.random();
return this;
},
getUserId: function() {
return this.userId;
}
}
var output = controller.fnFormatUserName('Manju').fnCreateUserId().getUserId();
document.body.innerHTML = output;
另一个版本可能是
var controller = {
currentUser: '',
fnFormatUserName: function(user) {
if (arguments.length == 0) {
return this.currentUser;
} else {
this.currentUser = user.toUpperCase();
return this;
}
},
fnCreateUserId: function() {
this.userId = this.currentUser + Math.random();
return this;
},
getUserId: function() {
return this.userId;
}
}
var output = controller.fnFormatUserName('Manju').fnCreateUserId().getUserId();
r1.innerHTML = output;
r2.innerHTML = controller.fnFormatUserName();
<div id="r1"></div>
<div id="r2"></div>
这篇关于javascript的链接方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!