Chaining methods with javascript

北城以北 提交于 2019-11-27 19:37:18

问题


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();

回答1:


As I already explained, since you are returning a string from fnFormatUserName you cannot use it for chaining.

To enable chaining, you need to return the object which invoked method. So, you cannot use getter methods for chaining.

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;

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>


来源:https://stackoverflow.com/questions/34898711/chaining-methods-with-javascript

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