原文:返回对象,使方法可以链式调用 - 每天一个JavaScript小知识@Js中文网 · 码农进阶题库

原文地址:https://www.javascriptc.com/interview-tips/zh_cn/javascript/return-objects-to-enable-chaining-of-functions/

在面向对象的Javascript中为对象建立一个方法时,返回当前对象可以让你在一条链上调用方法。

function Person(name) {
  this.name = name;

  this.sayName = function() {
    console.log("Hello my name is: ", this.name);
    return this;
  };

  this.changeName = function(name) {
    this.name = name;
    return this;
  };
}

var person = new Person("John");
person.sayName().changeName("Timmy").sayName();

扩展阅读: