链式调用的核心:调用完每个方法之后,返回自身示例this
class Method {method(param) {console.log(param);return this; //由于new 在实例化的时候this会指向创建的对象, 所以this.method这个方法会在原型链中找到。}}let m = new Method();m.method('第一次调用').method('第二次链式调用').method('第三次链式调用');
var obj = {a: function() {console.log("a");return this;},b: function() {console.log("b");return this;},};obj.a().b();
class LazyMan {constructor(name) {this.cb = [];console.log(`懒汉->${name}`);setTimeout(() => {this.next();});}sleep(time) {this.cb.push(() => {setTimeout(() => {console.log(`睡 --> ${time}s`);this.next();}, time * 1000);});return this;}sleepFirst(time) {this.cb.unshift(() => {setTimeout(() => {console.log(`先睡 --> ${time}s`);this.next();}, time * 1000);});return this;}eat(time) {this.cb.push(() => {setTimeout(() => {console.log(`吃 --> ${time}s`);this.next();}, time * 1000);});return this;}drink(time) {this.cb.push(() => {setTimeout(() => {console.log(`喝 --> ${time}s`);this.next();}, time * 1000);});return this;}next() {const fn = this.cb.shift();fn && fn();}}const lz = new LazyMan('sf');lz.eat(2).sleep(1).sleepFirst(5).drink(3);
