一次调用函数的多个方法

Joh*_*ohn 3 javascript methods prototype function

如果我有伪代码,如:

  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;
    };
  }
Run Code Online (Sandbox Code Playgroud)

我可以称之为:

user("John", "Smith").showName() // output : John Smith
Run Code Online (Sandbox Code Playgroud)

我想要的东西:

user("John", "Smith").changeName("Adam", "Smith").showName();
Run Code Online (Sandbox Code Playgroud)

and*_*lrc 7

在每个方法中返回对象.这被称为"链接".

  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
    };
}
Run Code Online (Sandbox Code Playgroud)

演示:http://jsbin.com/oromed/