JS链式调用方法

1,440 阅读1分钟

只需要在方法调用后返回this即可

    var user = function(name, age) {
      this.name = name;
      this.age = age;
    };
    user.prototype.getName = function() {
      console.log("姓名是",this.name);
      return this;
    };
    user.prototype.getAge = function() {
      console.log("年龄是",this.age);
      return this;
    };
    var user1 = new user("zjf", 22);
    user1.getName().getAge();
    //姓名是 zjf
    //年龄是 22

优点:可以像jQuery一样方便书写 缺点:在调试的时候,不容易找到错误点,即不利于维护