Chaining methods with javascript

后端 未结 1 798
时光说笑
时光说笑 2020-12-12 04:46

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.



        
1条回答
  •  [愿得一人]
    2020-12-12 05:39

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

    0 讨论(0)
提交回复
热议问题