JavaScript 中如何实现链式调用的函数?

新手上路,请多包涵
Sint(1,2).j(10) // 13

这样的函数怎么实现。

function Sint(a,b){
    this.val= a + b
}

Sint.prototype.j= function(e){
    return this.val + e
}

这样操作需要 new Sint(1,2) ,有什么办法可以实现直接 Sint(1,2).j(10) 输出结果吗?

阅读 503
4 个回答

补充一个思路,直接打印没法做到直接输出值,但是可以利用参与计算时,底层会调用 Symbol.toPrimitive 所绑定的方法,是可以做到直接跟运算符号的

function Sum(...args) {
    this.value = args.reduce((a, b) => a + b, 0);

    return new Proxy(this, {
        get: function (target, prop) {
            if (prop === Symbol.toPrimitive) {
                return () => target.value;
            }

            return target[prop];
        }
    });
}

Sum.prototype.add = function (value) {
    this.value += value;
    return this;
}

使用示例

// 访问值
new Sum(1,2,3).add(4).add(5).value // 15
// 参与计算
new Sum(1,2,3).add(4).add(5) + 20 // 35
let f = {
  name: 'dell',
  sayHi: function () {
    console.log(`hello, my name is ${this.name}`)
    return this
  },
  sayBye: function () {
    console.log(`byebye~~~~`)
    return this
  }
}
f.sayHi().sayBye()

可以参考这一篇:优雅的函数式编程

function Sint(a: number, b: number) {
  return {
    val: a + b,
    j: function (e: number) {
      return this.val + e;
    }
  }
 }

 console.log(Sint(1,2).j(10));   // 13
function Sint(a: number, b: number) : any {
  return new Proxy({} as {}, {
    get(target, prop) {
      if (prop === 'j') {
        return (e: number) => a + b + e;
      }
      return Reflect.get(target, prop);
    }
  })
}

console.log(Sint(1, 2).j(10));   // 13

持续链 那得加一个启动函数

function Sints(a: number, b: number) {
  return {
    _count : a + b,
    j: function (e: number) {
      this._count += e
      return this;
    },
    exec: function () {
      return this._count;
    }
  }
 }
 console.log(Sints(1,2).j(10).j(20).j(30).exec())
function Sint(a, b) {
    if (!(this instanceof Sint)) return new Sint(a, b)

    this._num = a + b
}

Object.defineProperties(Sint.prototype, {
    value: {
        get() {
            return this._num
        }
    },
    add: {
        value(n) {
            this._num += n
            return this
        }
    }
})

console.log(Sint(1, 2).add(10).add(-1).value) // 12
console.log(new Sint(1, 2).add(-1).add(-2).value) // 0
推荐问题
宣传栏