John
John

Reputation: 7880

call multiple methods of a function at one time

If I have pseudo code like :

  function user(a,b)
  {
    if(! (this instanceof user) ) return new user(a,b);
    this.a = a;
    this.b = b;
    this.showName = function() {
      alert(this.a + " " + this.b);
    };

    this.changeName = function(a,b) {
      this.a = a;
      this.b = b;
    };
  }

I can call it like :

user("John", "Smith").showName() // output : John Smith

I want something like :

user("John", "Smith").changeName("Adam", "Smith").showName();

Upvotes: 3

Views: 1259

Answers (1)

Andreas Louv
Andreas Louv

Reputation: 47099

Return the object in every method. This is called "chaining".

  function user(a,b)
  {
    if(! (this instanceof user) ) return new user(a,b);
    this.a = a;
    this.b = b;
    this.showName = function() {
      alert(this.a + " " + this.b);

      return this; // <--- returning this
    };

    this.changeName = function(a,b) {
      this.a = a;
      this.b = b;

      return this; // <--- returning this
    };
}

DEMO: http://jsbin.com/oromed/

Upvotes: 7

Related Questions