Chaining methods with javascript

2020-02-07 06:50发布

问题:

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>