链式调用的核心:调用完每个方法之后,返回自身示例this

    1. class Method {
    2. method(param) {
    3. console.log(param);
    4. return this; //由于new 在实例化的时候this会指向创建的对象, 所以this.method这个方法会在原型链中找到。
    5. }
    6. }
    7. let m = new Method();
    8. m.method('第一次调用').method('第二次链式调用').method('第三次链式调用');
    1. var obj = {
    2. a: function() {
    3. console.log("a");
    4. return this;
    5. },
    6. b: function() {
    7. console.log("b");
    8. return this;
    9. },
    10. };
    11. obj.a().b();
    1. class LazyMan {
    2. constructor(name) {
    3. this.cb = [];
    4. console.log(`懒汉->${name}`);
    5. setTimeout(() => {
    6. this.next();
    7. });
    8. }
    9. sleep(time) {
    10. this.cb.push(() => {
    11. setTimeout(() => {
    12. console.log(`睡 --> ${time}s`);
    13. this.next();
    14. }, time * 1000);
    15. });
    16. return this;
    17. }
    18. sleepFirst(time) {
    19. this.cb.unshift(() => {
    20. setTimeout(() => {
    21. console.log(`先睡 --> ${time}s`);
    22. this.next();
    23. }, time * 1000);
    24. });
    25. return this;
    26. }
    27. eat(time) {
    28. this.cb.push(() => {
    29. setTimeout(() => {
    30. console.log(`吃 --> ${time}s`);
    31. this.next();
    32. }, time * 1000);
    33. });
    34. return this;
    35. }
    36. drink(time) {
    37. this.cb.push(() => {
    38. setTimeout(() => {
    39. console.log(`喝 --> ${time}s`);
    40. this.next();
    41. }, time * 1000);
    42. });
    43. return this;
    44. }
    45. next() {
    46. const fn = this.cb.shift();
    47. fn && fn();
    48. }
    49. }
    50. const lz = new LazyMan('sf');
    51. lz.eat(2).sleep(1).sleepFirst(5).drink(3);