通过JavaScript中的链式方法实现JQuery的链式调用

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>js链式操作</title>
</head>

<body>
  <script>
    function A() {
      this.num = 2
    }
    A.prototype.set = function (num) {
      this.num = num;
      return this;   //将调用的对象返回就可以继续调用该对象里面的方法和对象了,即链式调用
    }
    A.prototype.get = function () {
      console.log(this.num);
      return this;
    }
    var B = new A();
    B.get().set(6).get();
    class Jack {
      constructor(x) {
        this.x = x;
      }
      get() {
        console.log(this.x);
        return this;
      }
      set(x) {
        this.x = x;
        return this;
      }
    }
    let j = new Jack(1);
    j.get().set(6).get();
  </script>
</body>

</html>

 

posted @ 2017-07-02 00:29  Tsingtree  阅读(475)  评论(0编辑  收藏  举报