简体   繁体   English

javascript的链接方法

[英]Chaining methods with javascript

I'm trying to create chaining with the javascript methods similar to what we have with jquery. 我正在尝试使用类似于jquery的javascript方法创建链接。 Please let me know how to implement chaining with javascript. 请让我知道如何使用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();

As I already explained, since you are returning a string from fnFormatUserName you cannot use it for chaining. 如前所述,由于您要从fnFormatUserName返回一个字符串,因此无法将其用于链接。

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 在您的示例中,处理该问题的方法是拥有getter方法和带有更新对象的方法,这些对象可用于链接,例如

 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; 


Another version could be 另一个版本可能是

 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM