链式操作

对象字面量创建对象

 var person = {
          foodCount: 10,
          eat: function () {
             this.foodCount--;
              return this;
          },
          buy: function () {
              this.foodCount++;
              return this;
          },
          print: function () {
              console.log(this.foodCount);
          }
 }
 //   foodCount初始值为10, 在连续吃了三次后,变为7
person.eat().eat().eat();
person.print(); //7

构造函数创建对象

function Person(){
         this.foodCount = 10,
         this.eat =  function () {
            this.foodCount--;
             return this;
         },
         this.buy = function () {
             this.foodCount++;
             return this;
         },
         this.print =  function () {
             console.log(this.foodCount);
         }
}
var lisi =  new Person() 
lisi.eat().eat().eat();
lisi.print(); //7

构造函数和原型一起创建对象

Person.prototype = {
           say: function() {
               console.log('I am saying');
               return this;
           }
}
function Person() {
           this.foodCount = 10, this.eat = function() {
               this.foodCount--;
               return this;
           }, this.buy = function() {
               this.foodCount++;
               return this;
           }, this.print = function() {
               console.log(this.foodCount);
           }
}
var lisi = new Person();
lisi.eat().eat().eat().say();  //I am saying
lisi.print(); //7

参考

JavaScript设计模式 --- 方法的链式调用 - CSDN博客 https://blog.csdn.net/CherishLyf/article/details/50517425

你可能感兴趣的:(链式操作)