3

如果我有类似的伪代码:

  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;
    };
  }

我可以这样称呼它:

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

我想要类似的东西:

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

1 回答 1

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
    };
}

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

于 2012-07-05T12:52:30.703 回答